go - golang规范中有关方法值的部分中的 'non-interface method'是什么意思?

标签 go methods interface specifications

The Go Programming Language Specification says :

As with selectors, a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).Mv.

和:

As with method calls, a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value: t.Mp is equivalent to (&t).Mp.

那么,给定上下文中的非接口(interface)方法是什么?

最佳答案

接口(interface)方法意味着您引用(调用)的方法是对接口(interface)值(其方法集包含该方法)的调用。同样,非接口(interface)方法意味着您引用(调用)的方法不是对接口(interface)值的调用(而是对具体类型的调用)。

例如:

var r io.Reader = os.Stdin
r.Read(nil) // Interface method: type of r is an interface (io.Reader)

var p image.Point = image.Point{}
p.String() // Non-interface method, p is a concrete type (image.Point)

要演示自动取消引用和地址获取,请参阅以下示例:

type myint int

func (m myint) ValueInt() int { return int(m) }

func (m *myint) PtrInt() int { return int(*m) }

func main() {
    var m myint = myint(1)

    fmt.Println(m.ValueInt()) // Normal
    fmt.Println(m.PtrInt())   // (&m).PtrInt()

    var p *myint = new(myint)
    *p = myint(2)

    fmt.Println(p.ValueInt()) // (*p).ValueInt()
    fmt.Println(p.PtrInt())   // Normal
}

它输出(在 Go Playground 上尝试):

1
1
2
2

关于go - golang规范中有关方法值的部分中的 'non-interface method'是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57648912/

相关文章:

http - Golang Wasm HTTP请求失败

algorithm - Iterative recurrent... 迭代法

String 类的 Java 1.6 方法不适用于所有字符

c# - 将 List<T> 作为接口(interface)上的属性

json - 具有嵌套属性的 Golang YAML 到 JSON

XML 解析/解码不返回任何内容

regex - 如何仅匹配一个字母词

java - 如何检查我的表中是否存在变量?

Objective-C @interface/指针澄清

objective-c - 没有可见的@interface