This question already has an answer here:
I am very confused about the following Go code. Who can tell me why
worker=u
and work=&u
are valid?worker=p
is valid?worker=&p
is invalid?package main
import (
"fmt"
)
type Worker interface {
Work()
}
type User struct {
name string
}
func (u User) Work() {
}
type People struct {
name string
}
func (p *People) Work() {
}
func main() {
var worker Worker
u := User{name:"xxx"}
worker = u // valid
worker = &u // valid
p := People{name:"xxx"}
worker = p // invalid
worker = &p // valid
}
</div>
worker=u
and work=&u
are valid because User
implement all methods of Worker
in this case only Work
method with values for receivers. Value methods can be invoked on both value and pointer.
worker=p
is invalid as People
implements Work
method with with pointer for receivers. So if you assign any value of People
to Worker
pointer then if will not Work
method. That's why it is invalid.
worker=&p
is valid as People
implements Work
method.
User and People are two different struct that implement same interface Worker
. This ensures that both have a method named Work
but the implementation may be different.
package main
import (
"fmt"
)
type Worker interface {
Work()
}
type User struct {
name string
}
func (u User) Work() {
fmt.Printf("Name : %s
", u.name)
}
type People struct {
name string
}
func (p *People) Work() {
fmt.Printf("Name : %s
", p.name)
}
func main() {
var worker Worker
u := User{name: "uuu"}
worker = u // valid
worker = &u // valid
worker.Work()
p := People{name: "pppp"}
// worker = p // invalid
worker = &p // valid
worker.Work()
}