结构体中指向接口的指针模拟错误

huangapple go评论76阅读模式
英文:

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类型的模拟实现。

你可以通过两种方式来修复这个问题。

  1. Personmoth字段类型改为Talker
type Person struct {
    moth Talker
}

或者

  1. 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.

  1. Change the Person's moth field's type to Talker.
type Person struct {
    moth Talker
}

or

  1. pass pointer reference of mockTalker to the person initialization`
person := Person{moth: &mockTalker}

huangapple
  • 本文由 发表于 2021年12月23日 05:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70455564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定