skip to content
Alvin Lucillo

Pointer receiver and interface

/ 2 min read

💻 Tech

In Go, some values don’t have address like constant values. They only become available during compile time but not during runtime. There’s nothing to share across the code, that’s why when we use constant values to call the add() method on the type with pointer receiver, it couldn’t call the pointer method. Note that even if the data type is non-pointer, it still works. The issue here is using a constant value.

A rule of thumb is to when defining data type, always keep in mind whether the program will interact with it in data or pointer semantics then stick with it.

type add interface {
	add()
}

type number int

func (n *number) add() {
	fmt.Println("add operation")
}

func main() {
	n := number(12) 
	n.add() // n is not a pointer but works

    nptr := &n
	n.add() // n is a pointer
	(&n).add() // using the address without creating a new variable
	(*number).add(&n) // another flavor of calling a method

	number(34).add() // error: cannot call pointer method add on number
	(*number).add(56) // error: cannot use 56 (untyped int constant) as *number value in argument to (*number).add
}
add operation
add operation
add operation
add operation
./prog.go:23:13: cannot call pointer method add on number
./prog.go:24:16: cannot use 56 (untyped int constant) as *number value in argument to (*number).add