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

关于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
    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
    
    点赞 评论
  • doujing1156
    doujing1156 2019-08-25 19:40
    type T struct {}
    
    func (t *T) f() {}
    
    func main() {
      x := T{}
      x.f()
    }
    

    Above, x.f is a non-interface method.

    点赞 评论

相关推荐