"<类型>是指向接口的指针,而不是接口"困惑 [英] "<type> is pointer to interface, not interface" confusion

查看:30
本文介绍了"<类型>是指向接口的指针,而不是接口"困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,对我来说似乎有点奇怪.看看这段代码:

I have this problem which seems a bit weird to me. Take a look at this snippet of code:

package coreinterfaces

type FilterInterface interface {
    Filter(s *string) bool
}

type FieldFilter struct {
    Key string
    Val string
}

func (ff *FieldFilter) Filter(s *string) bool {
    // Some code
}

type FilterMapInterface interface {
    AddFilter(f *FilterInterface) uuid.UUID     
    RemoveFilter(i uuid.UUID)                   
    GetFilterByID(i uuid.UUID) *FilterInterface
}

type FilterMap struct {
    mutex   sync.Mutex
    Filters map[uuid.UUID]FilterInterface
}

func (fp *FilterMap) AddFilter(f *FilterInterface) uuid.UUID {
    // Some code
}

func (fp *FilterMap) RemoveFilter(i uuid.UUID) {
    // Some code
}

func (fp *FilterMap) GetFilterByID(i uuid.UUID) *FilterInterface {
    // Some code
}

在其他一些包上,我有以下代码:

On some other package, I have the following code:

func DoFilter() {
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(fieldfilter) // <--- Exception is raised here
}

运行时不会接受提到的行,因为

The run-time won't accept the line mentioned because

"不能使用 fieldfilter (type *coreinterfaces.FieldFilter) 作为类型*coreinterfaces.FilterInterface 在 fieldint.AddFilter 的参数中:*coreinterfaces.FilterInterface 是指向接口的指针,而不是接口"

"cannot use fieldfilter (type *coreinterfaces.FieldFilter) as type *coreinterfaces.FilterInterface in argument to fieldint.AddFilter: *coreinterfaces.FilterInterface is pointer to interface, not interface"

但是,当将代码更改为:

However, when changing the code to:

func DoBid() error {
    bs := string(b)
    var ifilterfield coreinterfaces.FilterInterface
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    ifilterfield = fieldfilter
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(&ifilterfield)
}

一切正常,在调试应用程序时,它似乎确实包含了

Everything is alright and when debugging the application it really seems to include

我对这个话题有点困惑.在查看其他博客文章和讨论这个完全相同问题的堆栈溢出线程时(例如 - 这个,或这个) 第一个片段引发此异常应该有效,因为 fieldfilter 和 fieldmap 都被初始化为指向接口的指针,而不是接口的值.我一直无法理解这里实际发生的事情,我需要更改以便我不声明 FieldInterface 并为该接口分配实现.必须有一种优雅的方式来做到这一点.

I'm a bit confused on this topic. When looking at other blog posts and stack overflow threads discussing this exact same issue (for example - This, or This) the first snippet which raises this exception should work, because both fieldfilter and fieldmap are initialized as pointers to interfaces, rather than value of interfaces. I haven't been able to wrap my head around what actually happens here that I need to change in order for me not to declare a FieldInterface and assign the implementation for that interface. There must be an elegant way to do this.

推荐答案

所以你在这里混淆了两个概念.指向结构的指针和指向接口的指针不同.接口可以直接存储结构指向结构的指针.在后一种情况下,您仍然只是直接使用接口,不是指向接口的指针.例如:

So you're confusing two concepts here. A pointer to a struct and a pointer to an interface are not the same. An interface can store either a struct directly or a pointer to a struct. In the latter case, you still just use the interface directly, not a pointer to the interface. For example:

type Fooer interface {
    Dummy()
}

type Foo struct{}

func (f Foo) Dummy() {}

func main() {
    var f1 Foo
    var f2 *Foo = &Foo{}

    DoFoo(f1)
    DoFoo(f2)
}

func DoFoo(f Fooer) {
    fmt.Printf("[%T] %+v
", f, f)
}

输出:

[main.Foo] {}
[*main.Foo] &{}

https://play.golang.org/p/I7H_pv5H3Xl

在这两种情况下,DoFoo 中的 f 变量只是一个接口,不是指向接口的指针.然而,当存储f2时,接口持有一个指向Foo结构的指针.

In both cases, the f variable in DoFoo is just an interface, not a pointer to an interface. However, when storing f2, the interface holds a pointer to a Foo structure.

指向接口的指针几乎从不有用.事实上,Go 运行时被专门更改了几个版本,不再自动取消引用接口指针(就像结构指针一样),以阻止它们的使用.在绝大多数情况下,指向接口的指针反映了对接口应该如何工作的误解.

Pointers to interfaces are almost never useful. In fact, the Go runtime was specifically changed a few versions back to no longer automatically dereference interface pointers (like it does for structure pointers), to discourage their use. In the overwhelming majority of cases, a pointer to an interface reflects a misunderstanding of how interfaces are supposed to work.

但是,接口有限制.如果您将结构直接传递给接口,则只有该类型的 value 方法(即 func (f Foo) Dummy(),而不是 func (f *Foo) Dummy()) 可用于实现接口.这是因为您在接口中存储了原始结构的副本,因此指针方法会产生意想不到的效果(即无法更改原始结构).因此,默认的经验法则是在接口中存储指向结构的指针,除非有令人信服的理由不这样做.

However, there is a limitation on interfaces. If you pass a structure directly into an interface, only value methods of that type (ie. func (f Foo) Dummy(), not func (f *Foo) Dummy()) can be used to fulfill the interface. This is because you're storing a copy of the original structure in the interface, so pointer methods would have unexpected effects (ie. unable to alter the original structure). Thus the default rule of thumb is to store pointers to structures in interfaces, unless there's a compelling reason not to.

特别是您的代码,如果您将 AddFilter 函数签名更改为:

Specifically with your code, if you change the AddFilter function signature to:

func (fp *FilterMap) AddFilter(f FilterInterface) uuid.UUID

和 GetFilterByID 签名:

And the GetFilterByID signature to:

func (fp *FilterMap) GetFilterByID(i uuid.UUID) FilterInterface

您的代码将按预期工作.fieldfilter 属于 *FieldFilter 类型,它填充了 FilterInterface 接口类型,因此 AddFilter 会接受它.

Your code will work as expected. fieldfilter is of type *FieldFilter, which fullfills the FilterInterface interface type, and thus AddFilter will accept it.

这里有一些很好的参考资料,可以帮助您了解 Go 中的方法、类型和接口如何工作和相互集成:

Here's a couple of good references for understanding how methods, types, and interfaces work and integrate with each other in Go:

这篇关于&quot;&lt;类型&gt;是指向接口的指针,而不是接口"困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆