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

/*
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())
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值