如何构建一个接口作为函数的参数?
type blahinterface interface {
method1()
method2()
method3()
}
func blah (i blahinterface) {
}
blah(?) < what goes in here
答案 0 :(得分:2)
实际上,如果你试图在这里放置任何东西,编译器会准确地告诉你缺少什么:
type S struct{}
func main() {
fmt.Println("Hello, playground")
s := &S{}
blah(s)
}
go build
on this example会告诉您:
prog.go:20: cannot use s (type *S) as type blahinterface in argument to blah:
*S does not implement blahinterface (missing method1 method)
[process exited with non-zero status]
但是:
func (s *S) method1(){}
func (s *S) method2(){}
func (s *S) method3(){}
即使没有 reading about interfaces ,您也会受到指导,可以猜出缺少的内容。