1
type T struct {
    Tp int
}

func (t T) Set(a int) {

    t.Tp = a
}
func main() {
    t := T{}
    fmt.Println(reflect.TypeOf(t.Set))
    fmt.Println(reflect.TypeOf(T.Set))
}

result :
func(int)
func(main.T, int)

why T.set is not equal to t.set?
what is principle or translation bebind this?

http://play.golang.org/p/xYnWZ3PlyF

1 Answer 1

3

t.Set is a method value. T.Set is a method expression.

The method value t.Set yields a function equivalent to:

func(a int) ( t.Set(a) }

The method expression T.Set yields a function that is equivalent to the method with the receiver as the first argument.

func(t T, a int) { t.Set(a) }

This playground example illustrates the difference between the method value and method expression.

Separate from this discussion about method expressions and method values, the function Set should take a pointer receiver. Otherwise, the change to t is discarded.

func (t *T) Set(a int) {
   t.Tp = a
}

Here's the example with the pointer receiver.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice explanation, but I think T.Set is expression and t.Set is value. Typo I think?
Really helpful ! Solve the problem confused me all day long Thanks@3fo3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.