接口使用疑问
golangC++
package main
import "fmt"
type user struct {
name string
email string
}
type notifier interface {
notify()
}
func (u *user) notify() {
fmt.Printf("sending user email to %s<%s>\n",
u.name,
u.email)
}
func sendNotification(n notifier) {
n.notify()
}
func main() {
u := user{
name: "stormzhu",
email: "abc@qq.com",
}
sendNotification(u)
}
// compile error
// cannot use u (type user) as type notifier in argument to sendNotification:
// user does not implement notifier (notify method has pointer receiver)
unotifier*useruseruusernotifier
sendNotification(&u) T*T
接口的定义
go
type iface struct {
tab *itab // 类型信息
data unsafe.Pointer //实际对象指针
}
type itab struct {
inter *interfacetype // 接口类型
_type *_type // 实际对象类型
fun [1]uintptr // 实际对象方法地址
}
C++vptrvtable
方法集
同样参考雨痕《Go语言学习笔记》第6章6.3节,书中总结的很全面:
Treceiver T*Treceiver T + *TSTreceiver T + S*STreceiver T + S + *SS*S*Treceiver T + *T + S + *S
*TT*T
uusernotifier
T*TT*T
一些例子
goerror
type error interface {
Error() string
}
errors
// Package errors implements functions to manipulate errors.
package errors
// New returns an error that formats as the given text.
func New(text string) error {
return &errorString{text}
}
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
Newerror*errorStringNew&errorString{text}errorString{text}
总结
T*T*Treceiver T + *TTreceiver T