struct匿名字段和interface,断言

本文探讨了Go语言中接口Interface Men的实现,包括Human、Student和Employee三种类型。这些类型都包含了实现Interface Men所需的两个方法。通过接口断言,可以将Interface Men的对象转换为具体类型,并利用String方法进行输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 定义interface
type Men interface {
SayHi()
Sing(lyrics string)
}

type Human struct {
name string
age int
phone string
} 
type Student struct {
Human //匿名字段
school string
loan float32
}
//Human实现SayHi方法
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
} 
//Human实现Sing方法
func (h Human) Sing(lyrics string) {
fmt.Println("La la la la...", lyrics)
} 
//Employee重载Human的SayHi方法
func (e Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone)
}

Interface MenHuman,StudentEmployee实现,
为这三个型都实现两个方法,Interface Men的值可以是实现了该接口的任一对象。任何对象只要定义了String方法,都可以用Printf输出函数输出,如下:

type Element interface{}
type List [] Element
type Person struct {
name string
age int
} 
//定义了String方法,实现了fmt.Stringer
func (p Person) String() string {
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
} 
func main() {
list := make(List, 3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"Dennis", 70}
// Go语言里面有一个语法,可以直接判断某个接口是否是该类型的变量(断言assert interface.(type))
// value, ok = element.(T)
for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is of a different type\n", index)
}
}
}
//另外一种使用switch的用法:
for index, element := range list{
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index,
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", inde
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", inde
default:
fmt.Println("list[%d] is of a different type", index)
}
}
//嵌入interface,类似匿名字段
// io.ReadWriter可以使用Reader和Writer中的所有方法
type ReadWriter interface {
Reader
Writer
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值