我是Go的新手,不明白一件事。讓我們看一個(gè)有效的代碼:package mainimport "fmt"type User struct { Name string Email string}type Admin struct { User Level string}type Notifier interface { notify()}func (u *User) notify() { fmt.Println("Notified", u.Name)}func SendNotification(notify Notifier) { notify.notify()}func main() { admin := Admin{ User: User{ Name: "john smith", Email: "john@email.com", }, Level: "super", } SendNotification(&admin) admin.User.notify() admin.notify()}此處的函數(shù) SendNotification 將 admin 結(jié)構(gòu)識(shí)別為通告程序,因?yàn)?admin struct 可以訪問(wèn)通過(guò)指針接收器實(shí)現(xiàn)接口的嵌入式用戶結(jié)構(gòu)。還行。為什么下面的代碼不起作用。為什么norgateMathError需要實(shí)現(xiàn)接口而不使用錯(cuò)誤錯(cuò)誤的實(shí)現(xiàn)(對(duì)我來(lái)說(shuō)是同樣的情況):package mainimport ( "fmt" "log")type norgateMathError struct { lat string long string err error}// func (n norgateMathError) Error() string {// return fmt.Sprintf("a norgate math error occured: %v %v %v", n.lat, n.long, n.err)// }func main() { _, err := sqrt(-10.23) if err != nil { log.Println(err) }}func sqrt(f float64) (float64, error) { if f < 0 { nme := fmt.Errorf("norgate math redux: square root of negative number: %v", f) return 0, &norgateMathError{"50.2289 N", "99.4656 W", nme} } return 42, nil}.\custom_error.go:28:13: cannot use &norgateMathError{...} (type *norgateMathError) as type error in return argument: *norgateMathError does not implement error (missing Error method)
Go 接口繼承
月關(guān)寶盒
2022-08-24 17:04:13