為什么具有相同方法的兩個命名接口被視為不同的接口 - 如何避免這種情況?假設我們有一個喜歡吃產品的人(Eater)。他不在乎他是什么產品,他只想被指出從哪里可以買到新產品。換句話說,他想要產品服務,但并不關心產品服務會生產什么產品。在具體的實現中我們會盡量給他喂蘋果,所以我們會給他提供appleService。結果如下:./main.go:9: cannot use appleService (type *service.AppleService) as type eater.ProductServiceI in function argument: *service.AppleService does not implement eater.ProductServiceI (wrong type for New method) have New() service.ProductI want New() eater.ProductI接口service.AppleI和eater.AppleI具有相同的方法Eat(),除了 golang 將它們視為不同的方法。為什么以及如何避免這種情況?根據鴨子輸入,這應該有效,因為實際ProductServiceI需要的是提供的結構具有Eat()方法 - 它不應該關心什么名稱具有接口(service.ProductIvs eater.ProductI)。下面是完整代碼:==> ./main.go <==package mainimport "./apple/service"import "./eater"func main() { appleService := &service.AppleService{} // func eater.New(productService ProductServiceI) appleEater := eater.New(appleService) appleEater.EatUntilHappy()}==> ./eater/eater.go <==package eatertype ProductServiceI interface { New() ProductI}type ProductI interface { Eat()}type Eater struct { productService ProductServiceI}func New(productService ProductServiceI) *Eater { return &Eater{ productService: productService, }}func (a *Eater) EatUntilHappy() { for i:=0; i < 5; i++ { product := a.productService.New() product.Eat() }}==> ./apple/service/service.go <==package serviceimport "./apple"type ProductI interface { Eat()}type AppleService struct {}func (a *AppleService) New() ProductI { return &apple.Apple{}}==> ./apple/service/apple/apple.go <==package appleimport "fmt"type Apple struct {}func (a *Apple) Eat() { fmt.Println("mniam, mniam")}我認為只要聲明相同,什么名稱或什么導入路徑都有接口并不重要。
接口具有相同的方法,但被認為是不同的
慕婉清6462132
2021-07-16 18:15:13