美文网首页
golang interface:传指针还是对像

golang interface:传指针还是对像

作者: 小石头成长记 | 来源:发表于2019-12-13 19:43 被阅读0次

当定义了一个interface,传参时需要注意实现函数对interface的实现是基于指针的还是对像的。传参时需要与实现对应,否则会编译报错。
如下例Hello对Callback 的实现是基于指针的func (h *Hello) Myprint(str string) ,则在testCallback(&Hello{})时传的是指针;不能用testCallback(Hello{})。
如果改成func (h Hello) Myprint(str string),则可以用testCallback(Hello{})。


type Hello struct {
}

func (h *Hello) Myprint(str string){
    fmt.Println("this is a callback,",str);
    return 
}

type Callback interface {
    Myprint(str string) 
}

func testCallback (c Callback){
    c.Myprint("hello");
    fmt.Println("this is a test callback");
}

func main() {
    testCallback(&Hello{})
}

相关文章

网友评论

      本文标题:golang interface:传指针还是对像

      本文链接:https://www.haomeiwen.com/subject/gwlqnctx.html