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 Men被Human,Student和Employee实现,
因为这三个类型都实现了这两个方法,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
- struct匿名字段和interface,断言
- struct interface
- Java中接口(interface)和匿名类
- Java中接口(interface)和匿名类
- Java中接口(interface)和匿名类
- Golang--interface断言
- Go学习笔记 (二) : 流程控制(if,for,switch) 与 函数 与 struct (匿名字段)
- struct class interface abstract
- struct 的匿名成员
- class、interface、struct的区别
- golang中interface{}转为struct
- golang 接口interface{}、断言、switch type
- golang学习之Interface类型断言
- go 匿名字段
- struct和typedef struct
- struct和typedef struct
- struct和typedef struct
- struct 和 typedef struct
- 统计int数组中重复数字的个数
- FreeMarker Servlet 的配置 (web.xml)
- Android系统ANR以及Force Close出现的原因以及解决办法
- Java代理模式
- 多线程编程之NSOperationQueue
- struct匿名字段和interface,断言
- 线程总结
- FreeMarker在Web应用中的配置
- C++14新特性总结
- jQuery中Ajax事件请求状态
- 支付宝支付失败:4000
- JVM内存模型和关键参数设置
- Java NIO系列教程(四) Scatter/Gather
- ServletConfig与ServletContext