Re: [go-nuts] 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!
Thanks for your explanation. Ian Lance Taylor 于2023年6月4日周日 01:09写道: > On Sat, Jun 3, 2023 at 10:05 AM 王谦铭 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 > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJneERqEAMsJV-2FMoPx9F2cQGdtjFqJp8X57DyX0xW%3DN9Wx7w%40mail.gmail.com.
[go-nuts] 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!
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) } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/510a9f1b-bdd9-4715-b7a8-228f1fcd92bcn%40googlegroups.com.