我知道函数可以作为参数传递。但我想使用一个函数,该函数采用实现接口的类型作为函数的输入。这还有可能吗?
我已经尝试了以下,它给出cannot use myfn1 (type func(int)) as type fn in argument to test了错误。
package main
import "fmt"
type intf interface{}
type fn func(i intf)
func myfn1(i int) {
fmt.Printf("\ni is %v", i)
}
func myfn2(i int) {
fmt.Printf("\ni is %v", i)
}
func test(f fn, val int) {
f(val)
}
func main() {
test(fn(myfn1), 123)
test(myfn2, 321)
}
你可以试试: https: //play.golang.org/p/Al7USxzmYST
更改type fn func(i intf)为type fn func(i int)当然可以解决问题。但我不明白它是否可以与界面一起使用。
胡子哥哥
相关分类