struct匿名字段和interface,断言

来源:互联网 发布:域名加空间多少钱 编辑:程序博客网 时间:2024/05/16 08:20

// 定义interfacetype Men interface {SayHi()Sing(lyrics string)}type Human struct {name stringage intphone string} type Student struct {Human //匿名字段school stringloan 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 [] Elementtype Person struct {name stringage int} 
//定义了String方法,实现了fmt.Stringerfunc (p Person) String() string {return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"} 
func main() {list := make(List, 3)list[0] = 1 // an intlist[1] = "Hello" // a stringlist[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", indecase Person:fmt.Printf("list[%d] is a Person and its value is %s\n", indedefault:fmt.Println("list[%d] is of a different type", index)}}
//嵌入interface,类似匿名字段
// io.ReadWriter可以使用Reader和Writer中的所有方法type ReadWriter interface {ReaderWriter}



0 0
原创粉丝点击