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

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

接口具有相同的方法,但被認為是不同的

接口具有相同的方法,但被認為是不同的

Go
慕婉清6462132 2021-07-16 18:15:13
為什么具有相同方法的兩個命名接口被視為不同的接口 - 如何避免這種情況?假設我們有一個喜歡吃產品的人(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")}我認為只要聲明相同,什么名稱或什么導入路徑都有接口并不重要。
查看完整描述

3 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

只是為了完成:如果您在接口中使用私有方法(小寫方法名稱),可能會發生非常相似的情況(存在具有相同簽名的方法,但 Go 找不到它們)。

這樣,Go 將其對方法的搜索限制在定義接口的包中,因此不會在實現該方法的包中找到方法。

實際上,我想不出在公共接口中使用私有方法的任何合理理由:對接口的方法使用與接口本身相同的可見性。


查看完整回答
反對 回復 2021-07-19
  • 3 回答
  • 0 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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