Go Methods: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 18: Line 18:
The declaration is identical to that of a regular function, with the exception of the '''receiver parameter''', which precedes the function name. The receiver parameter gives the method's body access to the instance of the associated type. Aside from its special syntactical position, all other aspects the receiver parameter is identical with the regular parameters of the function.
The declaration is identical to that of a regular function, with the exception of the '''receiver parameter''', which precedes the function name. The receiver parameter gives the method's body access to the instance of the associated type. Aside from its special syntactical position, all other aspects the receiver parameter is identical with the regular parameters of the function.


An aspect that has profound implications on the relationship between the method and the type instance is whether the receiver parameter is a value or a pointer.
An aspect that has profound implications on the relationship between the method and the type instance is whether the receiver parameter is a value or a pointer. Use pointer receivers if you intend to let the method modify the state of the receiver instance. See [[#Value_or_Pointer_Receiver|Value or Pointer Receiver]].


=Value or Pointer Receiver=
=Value or Pointer Receiver=

Revision as of 00:56, 31 August 2024

External

Internal

Overview

Go allows associating arbitrary behavior with built-in or custom types, which contributes to the object-oriented character of the language. Note that Go is not a fully object-oriented language, it misses type inheritance, for example.

Syntactically, the association of the behavior with the type is done by declaring a function, encapsulating the behavior we want to add to the type, and adding a receiver type to its signature:

func (t ReceiverType) FunctionName(parameters, ...) (return_declaration) {
 ...
}

As result of this association, the function becomes a method of the type.

The declaration is identical to that of a regular function, with the exception of the receiver parameter, which precedes the function name. The receiver parameter gives the method's body access to the instance of the associated type. Aside from its special syntactical position, all other aspects the receiver parameter is identical with the regular parameters of the function.

An aspect that has profound implications on the relationship between the method and the type instance is whether the receiver parameter is a value or a pointer. Use pointer receivers if you intend to let the method modify the state of the receiver instance. See Value or Pointer Receiver.

Value or Pointer Receiver