Wednesday, 6 March 2024

Go Methods



In Go, methods are functions which are associated with some type; this type is called Receiver Type and methods are often called Receiver Functions. Their format is:

func (rcv RcvT) foo(arg1 TArg1, arg2 TArg2, ...) RtnT {
   ...
   // use rcv
}


This example shows some interesting properties of methods:


package main

import "fmt"

type MyInt struct {
i int
}

// associate function to a structure
// *MyInt is a Receiver type (here, it's a pointer type)
// multiply is now a Receiver function. From now on it requires a receiver in order to be called: (*MyInt).multiply
// When called on MyInt instance pointer, a copy of that pointer is passed to this function.
func (mi *MyInt) multiply(i int) {
mi.i = mi.i * i
}

// Receiver type can also be a value type.
// From now on it requires a receiver in order to be called: (MyInt).multiply
// When called on MyInt instance, a copy of that object is passed to this function.
func (mi MyInt) add(i int) {
mi.i = mi.i + i
}

func assign_struct_function_to_var(mi *MyInt) {
// Although function variable does not mention Receiver type...
var f func(i int)
// ...we can assign Receiver function to it!
f = mi.multiply

f(2)
fmt.Printf("%d\n", mi.i)

// function associated to struct can't be used in assignments on its own
// error:
// undefined: multiply
// f = multiply
}

func main() {
mi := MyInt{}
mi.i = 1
fmt.Printf("%d\n", mi.i)

// function associated to struct can't be invoked on its own
// error:
// undefined: multiply
// multiply(2)

assign_struct_function_to_var(&mi)
}

No comments: