Ily*_*yev 2 methods specifications interface go
与选择器一样,对具有使用指针的值接收器的非接口方法的引用将自动取消引用该指针:pt.Mv 等效于 (*pt).Mv。
和:
与方法调用一样,对具有使用可寻址值的指针接收器的非接口方法的引用将自动获取该值的地址:t.Mp 等价于 (&t).Mp。
那么,给定上下文中的非接口方法是什么?
Interface method means the method you refer to (you call) is a call on an interface value (whose method set contains the method). Similarly, non-interface method means the method you refer to (you call) is not a call on an interface value (but on a concrete type).
For example:
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)
Run Code Online (Sandbox Code Playgroud)
To demonstrate the auto-dereferencing and address taking, see this example:
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
}
Run Code Online (Sandbox Code Playgroud)
它输出(在Go Playground上尝试):
1
1
2
2
Run Code Online (Sandbox Code Playgroud)