Go Method Set for Type and Method Set for Pointer to Type

From NovaOrdis Knowledge Base
Revision as of 22:32, 1 September 2024 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

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

// ...

t := SomeType{}

// invoking the method with a value
t.SomeMethod()

// invoking the method with a pointer - the method is part of the method set
(&t).SomeMethod()