我想将一个指向函数的函数指针传递给“任何东西”。
打印从任何东西传入的东西很容易(如https://play.golang.org/p/gmOy6JWxGm0):
func printStuff(stuff interface{}) { fmt.Printf("Testing : %v", stuff) }
不过,假设我想这样做:
有多个结构
从各种功能加载数据
有一个为我调用该函数的通用打印
我在 Play ( https://play.golang.org/p/l3-OkL6tsMW ) 中尝试了这个,我收到以下错误:
./prog.go:35:12: 不能在 printStuff 的参数中使用 getStuff1 (type func() SomeObject) 作为类型 FuncType
./prog.go:36:12:不能在 printStuff 的参数中使用 getStuff2 (type func() SomeOtherObject) 作为类型 FuncType
万一播放的东西被删除,这是我试图弄清楚如何开始工作的代码:
package main
import (
"fmt"
)
type SomeObject struct {
Value string
}
type SomeOtherObject struct {
Value string
}
type FuncType func() interface{}
func getStuff1() SomeObject {
return SomeObject{
Value: "Hello, world!",
}
}
func getStuff2() SomeOtherObject {
return SomeOtherObject{
Value: "Another, hello!",
}
}
func printStuff(toCall FuncType) {
stuff := toCall()
fmt.Printf("Testing : %v", stuff)
}
func main() {
printStuff(getStuff1)
printStuff(getStuff2)
}
让这些东西正确通过的秘诀是什么?
天涯尽头无女友
相关分类