亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 接口繼承

Go 接口繼承

Go
月關寶盒 2022-08-24 17:04:13
我是Go的新手,不明白一件事。讓我們看一個有效的代碼: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: "[email protected]",        },        Level: "super",    }    SendNotification(&admin)    admin.User.notify()    admin.notify()}此處的函數 SendNotification 將 admin 結構識別為通告程序,因為 admin struct 可以訪問通過指針接收器實現接口的嵌入式用戶結構。還行。為什么下面的代碼不起作用。為什么norgateMathError需要實現接口而不使用錯誤錯誤的實現(對我來說是同樣的情況):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)
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

在第一種情況下,嵌入在 里面,因此可以獲得對類型上定義的所有方法的訪問。UserAdminAdminUser

在第二種情況下,具有類型字段,因此不會自動訪問其方法。norgateMathErrorerrError

如果你想有一個方法,你必須手動定義它norgateMathErrorError()

func (n norgateMathError) Error() string {
  return n.err.Error()
}

嵌入字段和僅包含字段之間是有區別的。更多信息可以在參考資料中找到


查看完整回答
反對 回復 2022-08-24
  • 1 回答
  • 0 關注
  • 91 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號