【发布时间】:2023-03-28 07:32:01
【问题描述】:
假设我有代码,其中一个函数接受另一个函数作为参数:
type Person struct {
Name string
}
func personBuilder() * Person {
return &Person{Name: "John"}
}
func printRetrievedItem(callback func() interface {}){
fmt.Print(callback());
}
func doStuff(){
printRetrievedItem(personBuilder);
}
这会导致错误cannot use personBuilder (type func() *Person) as type func() interface {} in function argument。如果我将personBuilder 返回类型更改为interface{},它可以工作,但在我正在处理的实际项目中,我希望有一个具体的类型用于清晰的设计和 TDD 目的。
Go 是否支持这种方法签名泛化?如果您无法更改 personBuilder 部分(例如,您有许多返回不同类型结构的无参数函数,并且您想构建一个接受任何这些构建器作为参数的消费者函数),有什么解决方法?
【问题讨论】:
标签: go