Uvelichitel
Uvelichitel

Reputation: 8490

What is the easy way to make method from function in Go?

It's quite trivial to get function from method using method expression

func (t T) Foo(){}
Foo := T.Foo       //yelds a function with signature Foo(t T)

Now suppose I already have

func Foo(t T)

can I get method T.Foo() without rewriting, or at least easy way?

Upvotes: 0

Views: 103

Answers (3)

Ainar-G
Ainar-G

Reputation: 36199

Others have already pointed out the best way to do this:

func (t T) Foo() { Foo(t) }

But if you for some reason need to do this at runtime, you can do something like this:

func (t *T) SetFoo(foo func(T)) {
    t.foo = foo
}

func (t T) CallFoo() {
    t.foo(t)
}

Playground: http://play.golang.org/p/A3G-V0moyH.

This is obviously not something you would normally do. Unless there is a reason, I'd suggest sticking with methods and functions as they are.

Upvotes: 1

Daniele D
Daniele D

Reputation: 939

Assuming T is a struct, you could:

func (t T) Foo() {
    Foo(t)
}

Upvotes: 2

helmbert
helmbert

Reputation: 37994

If you want to keep the function Foo(t T), for example for backwards-compatibility, you can simply define a struct method that calls the already-existing function:

type T struct {
    // ...
}

func Foo(t T) {
    // ...
}

// Define new method that just calls the Foo function
func (t T) Foo() {
    Foo(t)
}

Alternatively, you can easily change the function signature from func Foo(t T) to func (t T) Foo(). As long as you do not change the name of t, you will not have to rewrite the function itself any further.

Upvotes: 3

Related Questions