/*
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语言实现接口,接受者应该是传值还是传引用(传引用兼容传值)
最新推荐文章于 2024-06-14 12:49:16 发布