golang 接口interface 09

本文介绍了Go语言中接口的使用,包括如何与拥有相同方法的结构体关联、通过类型获取值以及简单工厂模式的应用。
摘要由CSDN通过智能技术生成

 1.接口会自动和拥有相同方法的结构体关联

/*
只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。
如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口。
*/
type MyInterface interface{
	GetName() string
	GetAge() int
}

type StringInterface interface{
	SumAgeSa() int
}

type CommonInterface interface{
	MyInterface
	StringInterface
	GetGender() string
}

type Employee struct {
	name   string
	age    int
	salary int
	gender string
}

func (self *Employee) GetName() string {
	return self.name
}

func (self *Employee) GetAge() int {
	return self.age
}

func (self *Employee) SumAgeSa() int {
	return self.age + self.salary
}

func (self *Employee) GetGender() string {
	return self.gender
}

/*自动关联上了*/
func IntRun()  {
	// 空接口的使用,空接口类型的变量可以保存任何类型的值
	// 空格口类型的变量非常类似于弱类型语言中的变量
	var varEmptyInterface interface{}
	fmt.Println("varEmptyInterface is of type %T\n", varEmptyInterface)
	varEmptyInterface = 100
	y := varEmptyInter
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值