zoukankan      html  css  js  c++  java
  • go语言规范之方法集

    Go语言规范里定义的方法集的规则

    Values        Methods Receivers
    -----------------------------------------------
      T          (t T)
      *T          (t T) and (t *T)
    

    T类型的值的方法集只包含值接收者声明的方法。而指向T类型的指针的方法集既包含值接收者声明的方法,也包含指针接收者声明的方法。

    从接收者类型的角度来看方法集

    Methods Receivers   Values 
    -----------------------------------------------
      (t T)         T and *T
      (t *T)         *T
    

    如果使用指针接收者来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。如果使用值接收者来实现一个接口,那么那个类型的值和指针都能够实现对应的接口。

    package main
    
    import "fmt"
    
    type duration int64
    
    func (d *duration) pretty() string  {
    	return fmt.Sprintf("Duration:%d",*d)
    }
    
    func main() {
    	duration(24).pretty()
    }
    
    

    上面的代码会出错

    goinaction/listing46.go:12:14: cannot call pointer method on duration(24)
    goinaction/listing46.go:12:14: cannot take the address of duration(24)
    

    修改为下方即可

    
    package main
    
    import "fmt"
    
    type duration int64
    
    func (d *duration) pretty() string  {
    	return fmt.Sprintf("Duration:%d",*d)
    }
    
    func main() {
    	s:=duration(24)
    	s.pretty()
    }
    
    

    原因接收者类型是个指针而不是函数传个int。
    s.pretty()在内部是(&s).pretty()

  • 相关阅读:
    dp学习笔记1
    hdu 4474
    hdu 1158(很好的一道dp题)
    dp学习笔记3
    dp学习笔记2
    hdu 4520+hdu 4522+hdu 4524(3月24号Tencent)
    hdu 1025(最长非递减子序列的n*log(n)求法)
    hdu 2063+hdu 1083(最大匹配数)
    hdu 1023
    《 Elementary Methods in Number Theory 》Exercise 1.3.12
  • 原文地址:https://www.cnblogs.com/c-x-a/p/11356213.html
Copyright © 2011-2022 走看看