go语言实现接口,接受者应该是传值还是传引用(传引用兼容传值)

来源:互联网 发布:轻松网络销售招聘 编辑:程序博客网 时间:2024/06/10 09:11
/*go语言中给接口赋值的时候,对象如果是值(对于引用的接受者处理不了)如果是指针,则可以自动实现值的处理 */package mainimport "fmt"//定义Integer类型type Integer inttype LessAddInf interface{Less(n Integer) boolAdd(n Integer) Integer}func (this Integer) Less(n Integer) bool{return this < n}func (this *Integer) Add(n Integer) Integer{*this += nreturn *this}type Computer struct{CPU string "计算器"Memory string "内存"}type Thing interface{Name() stringAttribute() string}func (this Computer) Name() string  {return "Computer"}func (this *Computer) Attribute()string  {return fmt.Sprintf("CPU=%v Memory=%v", this.CPU, this.Memory)}func main()  {var inf LessAddInfvar n Integerinf = &nfmt.Printf("inf.Less(20)=%v\n",inf.Less(20))fmt.Printf("inf.Add(30)=%v\n", inf.Add(30))var thing Thingvar computer = Computer{CPU:"英特尔至强-v3440", Memory:"三星DDR4(8g)"}thing = &computerfmt.Printf("thing.Name()=%v\n", thing.Name())fmt.Printf("thing.Attribute()=%v\n", thing.Attribute())}

1 0
原创粉丝点击