Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between interface pointer and interface value in golang

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) {}
like image 865
Mannix Suo Avatar asked Sep 05 '25 02:09

Mannix Suo


2 Answers

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{}.

like image 83
AJR Avatar answered Sep 07 '25 20:09

AJR


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)
}
like image 32
user13631587 Avatar answered Sep 07 '25 20:09

user13631587