Reputation: 124
When I studied Go by "Go In Action" book, there is a segment code like below.
I haven't learned Go too much in its interface concept.
The segment defines a interface called notifier used to notify people, and two types (user , admin) impl this interface.There is a middleware, says sendNotification(), that uniforms the type who impls notifier interface
What confuses me is the parameter of middleware function sendNotification(), it receives a value (not pointer!) of inferface type(notifier) .But, why uses a pointer to invoke this function in main function:
sendNodification(&lisa)
sendNodification(&bil)
?? just why?
windows 10. Go 1.12.2
package main
import "fmt"
type notifier interface {nodify()}
type user struct {name string;email string}
type admin struct{name string;email string}
func (u *user) nodify (){
fmt.Printf("sending user email to %s<%s>\n", u.name, u.email)
}
func (u *admin) nodify(){
fmt.Printf("sending admin email to %s<%s>\n", u.name, u.email)
}
func sendNodification(n notifier){
n.nodify()
}
func main(){
bil := user{"Bill", "[email protected]"}
sendNodification(&bil)
lisa := admin{"Lisa", "[email protected]"}
sendNodification(&lisa)
}
Upvotes: 0
Views: 98
Reputation: 46442
Because the methods are declared with pointer receivers (func (u *user) nodify
rather than func (u user) nodify
), it's the pointer to the type that implements the interface. So you can pass a *user
to a function accepting a notifier
because *user
implements the interface.
Upvotes: 3