atc0005 / notes

Various notes, quick references and topics I want to explore further
MIT License
0 stars 0 forks source link

Go | Receiver types, pointers, pass by value #52

Open atc0005 opened 2 years ago

atc0005 commented 2 years ago

The receiver is passed by value, including the pointer receiver: it is a copy, and changing its value doesn't change the initial pointer receiver on which the method is called.

See "Why are receivers pass by value in Go?".

Relevance:

Attempting to implement the flags.Value interface with a Set() method on a pointer that happens to be nil and attempting to assign a valid pointer to the method receiver in the Set() method (which isn't allowed).


This is clearly forbidden by the language spec. Spec: Method declarations:

The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be a defined type T or a pointer to a defined type T. T is called the receiver base type. A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method.

You can't declare a method with receiver type *T where T is already a pointer type, and you also cannot add methods for types defined in other packages. The type declaration and the method declaration must be in the same package.

Relevance:

Attempting to use a pointer to a type as the base which is already a pointer.

Refs: