您的位置:首页 > 编程语言 > Go语言

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

2016-10-27 20:57 274 查看
/*
go语言中给接口赋值的时候,对象如果是值(对于引用的接受者处理不了)
如果是指针,则可以自动实现值的处理
*/

package main

import "fmt"

//定义Integer类型
type Integer int

type LessAddInf interface{
Less(n Integer) bool
Add(n Integer) Integer
}

func (this Integer) Less(n Integer) bool{
return this < n
}

func (this *Integer) Add(n Integer) Integer{
*this += n
return *this
}

type Computer struct{
CPU string "计算器"
Memory string "内存"
}

type Thing interface{
Name() string
Attribute() 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 LessAddInf
var n Integer
inf = &n
fmt.Printf("inf.Less(20)=%v\n",inf.Less(20))
fmt.Printf("inf.Add(30)=%v\n", inf.Add(30))

var thing Thing
var computer = Computer{CPU:"英特尔至强-v3440", Memory:"三星DDR4(8g)"}
thing = &computer
fmt.Printf("thing.Name()=%v\n", thing.Name())
fmt.Printf("thing.Attribute()=%v\n", thing.Attribute())
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go
相关文章推荐