接口不能调用自检方法 [英] Interface can not call self method

查看:185
本文介绍了接口不能调用自检方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了两个功能.当我传递一个指向它的指针时,我无法获得已定义的方法.为什么会这样?

I have defined two functions. When I pass a pointer to it, I can't get the defined method. Why is this?

type Visitor interface {
    work()
}

func test(v *Visitor)  {
    v.work() // error
}


func test1(v Visitor)  {
    v.work() // ok
}

错误:

v.work未定义(类型* Visitor是指向接口的指针,不是 界面)

v.work undefined (type *Visitor is pointer to interface, not interface)

有人知道为什么,

推荐答案

func test(v *Visitor)  {
    v.work() // error
}

v.work()应该是一个方法调用.但是v的类型为*Visitor,它是指向接口的指针. 指向接口的指针具有0个方法,它不执行任何操作(空接口interface{}除外).

v.work() ought to be a method call. But v is of type *Visitor, a pointer to interface. A pointer to interface has 0 methods, it does not implement anything (except the empty interface interface{}).

使用非指针时,值v(或更确切地说,其类型)具有方法work(),因此您可以调用该方法:

When using a non-pointer, the value v (or rather its type) has a method work(), so you can call that:

func test(v Visitor)  {
    v.work() // ok
}

此处v.work()起作用,因为v属于接口的Visitor类型,并且包含方法work().

Here v.work() works, because the v is of type Visitor which is an interface, and it contains the method work().

可能令人困惑的是,如果将方法添加到(非指针,非接口)具体类型中,则相应的指针类型也将具有该方法,并且可以调用该方法.该文件位于规范:方法集:

What may be confusing is that if you add method to a (non-pointer, non-interface) concrete type, the respective pointer type will also have that method, and you can call that. This is in Spec: Method sets:

一种类型可能具有与之关联的方法集. 接口类型的方法集是其接口.任何 other 类型T的方法集都包含所有方法用接收器类型T声明. 相应的指针类型的方法集 *T是所有方法的集合用接收方*TT声明(也就是说,它还包含T的方法集).进一步的规则适用于包含嵌入字段的结构,如唯一方法名称.

A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.

区别在于您对接口类型尝试了相同的操作,这是行不通的.它适用于具体的(非接口)类型.教训是永远不要使用指向接口的指针,除非您可以推理为什么需要它(很少需要它).

The difference is that you tried the same with interface type, which won't work. It works with concrete (non-interface) types. Lesson is to never use pointer to interface unless you can reason why it is needed (it is rarely needed).

这篇关于接口不能调用自检方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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