调用一个将接口作为Go中的参数的函数

时间:2014-09-17 19:05:31

标签: go

如何构建一个接口作为函数的参数?

type blahinterface interface {
    method1()
    method2()
    method3()
}

func blah (i blahinterface) {

}


blah(?)  < what goes in here

1 个答案:

答案 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(){}

program do compile just fine

即使没有 reading about interfaces ,您也会受到指导,可以猜出缺少的内容。