I am new to Go, and I am studying its interface feature.
Here is the code:
package main
import (
"fmt"
"reflect"
)
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Integer) Add(b Integer) {
*a += b
}
type LessAdder interface {
Less(b Integer) bool
Add(b Integer)
}
var a Integer = 1
var b LessAdder = &a
func main() {
fmt.Println(reflect.TypeOf(b))
fmt.Println(b.Less(2))
b.Add(a)
fmt.Println(a)
}
And it will output the the following:
*main.Integer
true
2
Well, this works pretty well.
The Point is:
How var b LessAdder = &a
works. Does the pointer auto-dereference happens right here, or when b invokes member method?
The output *main.Integer
tells us that b is a pointer to type Integer
, hence it is the second case.
Then the tricky thing comes:
when I add fmt.Pringln(*b)
to the code, the compiler comes with an error:
demo/demo1
./demo1.go:31: invalid indirect of b (type LessAdder)
And it confuses me. Since b
is a pointer type to Integer
, then dereferencing it should work. But why not?