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

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

不能使用(類型函數(d 狗))作為類型函數(動物動物)

不能使用(類型函數(d 狗))作為類型函數(動物動物)

Go
寶慕林4294392 2022-10-04 19:54:15
我正在努力編寫一個方法可以同時將和方法作為其參數,而我的IDE告訴我:callGetNamegetCatNamegetDogName不能使用“獲取狗名”(類型函數(d 狗))作為類型函數(動物動物)package maintype Animal struct {    Name string}type Cat struct {    Animal}type Dog struct {    Animal}func getCatById(c Cat) {}func validateDogNames(d Dog) {}func invokeFunc(f func(animal Animal)) {}func main() {    invokeFunc(getCatById)    invokeFunc(validateDogNames)}我試圖分析原因,也許是因為高浪支持多重繼承?請讓我知道我是否在做一些愚蠢的事情,或者有沒有更好的方法來實現這一目標?========關于我為什么要嘗試這個:在go-kit框架中,我必須為每個定義的服務方法編寫makeEndpoint函數。我用反射來采用一個通用的制作端點,如下所示:func NewProductEndpoints() ProductEndpoints {    ps := service.NewProductService()    return ProductEndpoints{        GetProductById: makeEndpoint(ps, util.GetFunctionName(ps.GetProductById)),        CreateProduct: makeEndpoint(ps, util.GetFunctionName(ps.CreateProduct)),    }}func makeEndpoint(s service.ProductService, funcName string) kitEndpoint.Endpoint {    return func(ctx context.Context, request interface{}) (response interface{}, err error) {        req := request.(domain.ProductDTO)        currFunc := reflect.ValueOf(s).MethodByName(funcName)        args := []reflect.Value{reflect.ValueOf(req)}        res := currFunc.Call(args)[0]        return res, nil    }}想知道是否有更好的方法來實現。提前致謝。
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

所以你以一種相當OOP的方式思考,Go沒有繼承(澄清它有結構嵌入,這就是你在第一個例子中所做的)。我們傾向于用組合來解決問題。


您可以考慮解決問題的一種方法是如下所示。


package main


import (

    "fmt"

)


type Namer interface {

    Name() string

}


type Cat struct {

    name string

}


func (c Cat) Name() string {

    return c.name

}


type Dog struct {

    name string

}


func (d Dog) Name() string {

    return d.name

}


func PetName(n Namer) {

    fmt.Println(n.Name())

}


func main() {

    PetName(Dog{name: "Fido"})

    PetName(Cat{name: "Mittens"})

}

名稱可以改進,但它應作為可以采取的方法的基本示例。


編輯:基于下面留下的評論的示例


package main


import (

    "fmt"

)


type Invoker interface {

    Invoke()

}


type Dog struct{}


func (Dog) Bark() {

    fmt.Println("Woof")

}

func (d Dog) Invoke() {

    d.Bark()

}


type Cat struct{}


func (Cat) Meow() {

    fmt.Println("Meow")

}

func (c Cat) Invoke() {

    c.Meow()

}


func CallFunc(i Invoker) {

    i.Invoke()

}


func main() {

    CallFunc(Cat{})

    CallFunc(Dog{})

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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