duanchongzi9997 2019-08-25 19:02 采纳率: 0%
浏览 100
已采纳

关于golang规范中方法值的部分中的“非接口方法”是什么意思?

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.

and:

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.

So, what is non-interface method in the given context?

  • 写回答

2条回答 默认 最新

  • doudan5136 2019-08-25 19:40
    关注

    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)
    

    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
    }
    

    It outputs (try it on the Go Playground):

    1
    1
    2
    2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?