Go Method Set for Type and Method Set for Pointer to Type: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=Internal= * Go Method =Overview= A method defined with a value receiver can be always invoked on the pointer of the type. This is because given a poster, a value can always be obtained.") |
|||
(2 intermediate revisions by the same user not shown) | |||
Line 4: | Line 4: | ||
=Overview= | =Overview= | ||
A method defined with a value receiver can be always invoked | A method defined with a value receiver can be always invoked with a pointer of the type. This is because [[Pointers_in_Go#Pointers_Lead_to_Values,_the_Reciprocal_is_Not_Always_True|given a poster, a value can always be obtained]]. | ||
<syntaxhighlight lang='go'> | |||
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() | |||
</syntaxhighlight> | |||
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: | |||
<syntaxhighlight lang='go'> | |||
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() | |||
</syntaxhighlight> |
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()