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()) }
相关文章推荐
- Java 中到底是应该用接口类型 还是实现类的类类型去引用对象?
- C# 学习笔记(四) 结构体实现接口后是值类型还是引用类型
- ArrayList和LinkedList都是实现了List接口的类,他们都是元素的容器,用于存放对象的引用; 他们都可以对存放的元素进行增删改查的操作,还可以进行排序。 但是,他们还是有区别的。
- C#中结构体实现接口后是值类型还是引用类型
- C#Lab(一):结构体包含引用、结构体实现接口后是引用类型还是值类型
- C#中结构体实现接口后是值类型还是引用类型
- 实践javascript美术馆的小案例,学习到的东西还是蛮多的,包括javascript编程中的预留退路、分离javascript、以及实现向后兼容等
- Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?
- (JAVA子类引用指象父类引用)JAVA克隆对象,包括父类属性,无需实现序列化接口
- C++ 如何动态库实现接口兼容
- 智能指针里弱引用应该如何实现?(WeakReference/WeakPtr<T>)
- C++实现对象和接口的弱引用
- 实例化一个子类对象赋给父类对象引用或一个实现了接口的类的对象赋给接口的引用的好处
- 对于引用实现接口的类的对象
- [FxCop.设计规则]7. 集合类应该实现泛型接口
- Go语言服务器开发实现最简单HTTP的GET与POST接口
- Java初学习 - 多态和实现接口的类的对象赋值给接口引用的方法
- Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?
- C++ 如何动态库实现接口兼容
- Go语言的接口和实现类初探(二)