我是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 回答
- 0 關注
- 91 瀏覽
添加回答
舉報
0/150
提交
取消