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条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?