我試圖撰寫一個方法callGetName,它可以同時將getCatName和getDogName方法作為其引數,而我的 IDE 告訴我:
不能使用 'getDogName' (type func(d Dog)) 作為型別 func(animal Animal)
package main
type 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)
}
我試著分析了一下原因,可能是因為golang支持多重繼承?
請讓我知道我是否在做一些愚蠢的事情,或者有沒有更好的方法來實作這一目標?
========
關于我為什么要嘗試這個的更多資訊:在 go-kit 框架中,我必須為定義的每個服務方法撰寫 makeEndpoint 函式。我使用reflect采用了一個通用的makeEndpoints,如下所示:
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
}
}
想知道是否有更好的方法來實作。提前致謝。
uj5u.com熱心網友回復:
因此,您以一種相當 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{})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329744.html
