Go Method Set for Type and Method Set for Pointer to Type: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
// ...
// ...


// invoking the method with a value
SomeType{}.SomeMethod()
// invoking the method with a variable that contains a value
t := SomeType{}
t := SomeType{}
t.SomeMethod()
// invoking the method with a pointer - the method is part of the method set
(&t).SomeMethod()
</syntaxhighlight>


// invoking the method with a value
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()
t.SomeMethod()


// invoking the method with a pointer - the method is part of the method set
// of course, it can be invoked with a pointer
(&t).SomeMethod()
(&t).SomeMethod()
</syntaxhighlight>
</syntaxhighlight>

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()