Go Method Set for Type and Method Set for Pointer to Type: Difference between revisions
Jump to navigation
Jump to search
Line 36: | Line 36: | ||
// the pointer receiver type cannot be invoked with this value, this won't compile | // the pointer receiver type cannot be invoked with this value, this won't compile | ||
SomeType{}.SomeMethod() | // SomeType{}.SomeMethod() | ||
// the pointer receiver type can be invoked with a variable value | // the pointer receiver type can be invoked with a variable value |
Latest revision as of 22:46, 1 September 2024
Internal
Overview
A method defined with a value receiver can be always invoked with a pointer of the type. This is because given a poster, a value can always be obtained.
type SomeType struct {
i int
}
func (t SomeType) SomeMethod() {
fmt.Printf("invoked SomeMethod on %v\n", t)
}
// ...
// invoking the method with a value
SomeType{}.SomeMethod()
// invoking the method with a variable that contains a value
t := SomeType{}
t.SomeMethod()
// invoking the method with a pointer - the method is part of the method set
(&t).SomeMethod()
The reverse is not always true, there are situations when a pointer receiver method cannot be invoked with a value, because we cannot get a pointer to that value:
func (t *SomeType) SomeMethod() {
fmt.Printf("invoked SomeMethod on %p\n", t)
}
// the pointer receiver type cannot be invoked with this value, this won't compile
// SomeType{}.SomeMethod()
// the pointer receiver type can be invoked with a variable value
t := SomeType{}
t.SomeMethod()
// of course, it can be invoked with a pointer
(&t).SomeMethod()