第5章 Go语言的类型系统
5.4 接口
接口是用来定义行为的类型。这些被定义的行为不由接口直接实现,而是通过方法由用户定义的类型实现。如果用户定义的类型实现了某个接口类型声明的一组方法,那么这个用户定义的类型的值就可以给这个接口类型的赋值,从而实现多态(是指代码可以根据类型的具体实现采取不同行为的能力)。
package main
import "fmt"
type notifier interface {
notify()
}
type user struct {
name string
email string
}
func (u *user) notify() {
fmt.Printf("Sending user email to %s<%s>\n",
u.name,
u.email)
}
func sendNotifycation(n notifier) {
n.notify()
}
func main(){
u := user{"Bill", "bill@email.com"}
//Cannot use 'u' (type user) as the type notifier Type does not implement 'notifier' as the 'notify' method has a pointer receiver
//sendNotifycation(u)
sendNotifycation(&u)
}
output: Sending user email to Bill<bill@email.com>
方法集定义了接口的接收规则,即定义方法时使用的接收者类型决定了这个方法是关联到值还是指针。例如上面的u,是user类型的值,只能包含值接收者声明的方法,而user的notify方法是指针接收者声明的方法。
Go语言的接口定义了一组方法签名,类型通过实现这些方法来满足接口。接口的实现是隐式的,不需显式声明。在示例中,`user`类型通过指针接收者的方法`notify`实现了`notifier`接口,从而允许将`&u`传递给`sendNotification`实现多态。方法集决定了接口的接收规则,值接收者方法只能被值类型调用,指针接收者方法则需要指针类型调用。

2876

被折叠的 条评论
为什么被折叠?



