英文:
Struct with an pointer to an Interface mock error
问题
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(ctrl)
person := Person{moth: &mockTalker}
}
假设我已经使用mockgen为Talker接口创建了一个模拟对象。
当我创建Person{moth: mockTalker}
时,我遇到了错误。我无法传递mockTalker
。
英文:
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}
}
Assuming that I have already created a mock for Talker interface using mockgen.
I am getting error when I am creating Person{moth: mockTalker}
. I am not able to pass mockTalker
.
答案1
得分: 3
不要使用指针接口。本质上,接口是指针。
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()
}
英文:
Don't user pointer interface. Essentially interface is pointer
type Person struct {
moth Talker
}
Normally, if function want return interface
, it's will return new struct by pointer.
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()
}
答案2
得分: 1
在你的Person
结构体中,moth
字段是*Talker
类型。它是Talker
接口的指针类型。NewMockTalker(ctl)
返回Talker
类型的模拟实现。
你可以通过两种方式来修复这个问题。
- 将
Person
的moth
字段类型改为Talker
。
type Person struct {
moth Talker
}
或者
- 将
mockTalker
的指针引用传递给person
的初始化。
person := Person{moth: &mockTalker}
英文:
In your Person
struct the moth field is *Talker
type. It is a pointer type of Talker
interface. NewMockTalker(ctl)
returns Talker
type mock implementation.
You can do two things to fix this.
- Change the
Person
's moth field's type toTalker
.
type Person struct {
moth Talker
}
or
- pass pointer reference of
mockTalker
to theperson
initialization`
person := Person{moth: &mockTalker}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论