If a pointer type implements a method in an interface, then its value type variable cannot be assigned to the corresponding interface. But it works the other way around!

101 views
Skip to first unread message

王谦铭

unread,
Jun 3, 2023, 1:05:49 PM6/3/23
to golang-nuts
If a pointer type implements a method in an interface, then its value type variable cannot be assigned to the corresponding interface. Conversely, if a value type implements a method in an interface, its pointer type variable can be assigned to the corresponding interface. 
I want know why that can work? Just like the code. 
import "fmt"

type A struct {
}

type Changer1 interface {
change1()
}

type Changer2 interface {
change2()
}

func (a *A) change1() {
}

func (a A) change2() {
}

func main() {
var c1 Changer1
var c2 Changer2
a1 := A{}
a2 := &A{}
c1 = a1 //Wrong, the compilation failed, because the value type of A does not implement the change1() method, so a1, which is the value type of A, is not a Changer1
c1 = a2

c2 = a1
c2 = a2 //It turned out to be ok, the pointer type of A did not implement the change2() method, but a2, which is a pointer type of A, turned out to be a Changer2

//for compilation
fmt.Println(c1)
fmt.Println(c2)
}

Ian Lance Taylor

unread,
Jun 3, 2023, 1:10:09 PM6/3/23
to 王谦铭, golang-nuts
On Sat, Jun 3, 2023 at 10:05 AM 王谦铭 <wangqian...@gmail.com> wrote:
>
> If a pointer type implements a method in an interface, then its value type variable cannot be assigned to the corresponding interface. Conversely, if a value type implements a method in an interface, its pointer type variable can be assigned to the corresponding interface.
> I want know why that can work? Just like the code.

Please paste code as plain text or as a link to the Go playground. Thanks.

In Go every value method--that is, every method with a value
receiver--is also valid for the pointer type. See
https://go.dev/ref/spec#Method_sets .

Ian

王谦铭

unread,
Jun 4, 2023, 3:33:45 AM6/4/23
to Ian Lance Taylor, golang-nuts
Thanks for your explanation. 

Ian Lance Taylor <ia...@golang.org> 于2023年6月4日周日 01:09写道:
Reply all
Reply to author
Forward
0 new messages