当前位置: > > > > 带有指向接口模拟错误的指针的结构
带有指向接口模拟错误的指针的结构
来源:stackoverflow
2024-04-23 19:54:30
0浏览
收藏
积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《带有指向接口模拟错误的指针的结构》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
package main
import (
"github.com/golang/mock/gomock"
"testing"
)
type Talker interface {
talk() string
}
type Person struct {
moth *Talker
}
func (p *Person) speak() string {
return (*p.moth).talk()
}
func TestPerson(t *testing.T) {
ctrl := gomock.NewController(t)
mockTalker := NewMockTalker(ctl)
person := Person{moth: mockTalker}
}
假设我已经使用mockgen为talker接口创建了一个模拟。
创建 person{moth:mocktalker} 时出现错误。我无法通过 mocktalker。
正确答案
不要使用指针界面。本质上接口就是指针
type person struct {
moth talker
}
通常情况下,如果函数想要返回interface,它将通过指针返回新的结构体。
import "fmt"
type I interface {
M()
}
type S struct {
}
func (s *S) M() {
fmt.Println("M")
}
func NewI() I {
return &S{}
}
func main() {
i := NewI()
i.M()
}
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持米云!更多关于Golang的相关知识,也可关注米云公众号。
