when Node
is a struct type, it can't compiled.
but when Node
is a interface type it's ok.
why?
type Node interface {
}
// test1's parameter are pointer
func test1(b *Node) {
test2(b)
}
// test2's parameter are not pointer
func test2(c Node) {}
To answer the question in your title: an interface pointer is a pointer to an interface value. However, an interface pointer is not that useful as an interface is a reference type already.
As to why your code does not compile when Node
is a struct, you are trying to pass a pointer to a function that takes a value. You should do this instead:
func test1(b *Node) {
test2(*b)
}
But when Node
is an empty interface the parameter of test2()
is of type interface{}
also called the empty interface. Any type (including b
which is a pointer) will be implicitly converted to an empty interface. Hence passing anything to test2()
will compile when its parameter is of type interface{}
.
Let's look at some variations on the declaration of Node
:
Example 1:
type Node interface {
}
The code compiles because all types satisfy the empty interface.
Example 2:
type Node interface {
AnyMethod()
}
The compiler reports the following error:
cannot use b (type *Node) as type Node in argument to test2: *Node is pointer to interface, not interface
The compilation fails because a *Node
does not have the method AnyMethod
.
Example 3:
type Node struct {
}
The compiler reports the following error:
cannot use b (type *Node) as type Node in argument to test2
The compilation fails because *Node
and Node
are different types.
One fix for the compilation error is dereference the pointer:
func test1(b *Node) {
test2(*b)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With