我是Go的新手,不明白一件事。让我们看一个有效的代码:
package main
import "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()
}
此处的函数 SendNotification 将 admin 结构识别为通告程序,因为 admin struct 可以访问通过指针接收器实现接口的嵌入式用户结构。还行。为什么下面的代码不起作用。为什么norgateMathError需要实现接口而不使用错误错误的实现(对我来说是同样的情况):
package main
import (
"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)
泛舟湖上清波郎朗
相关分类