golang中的接口
2024-09-06 09:33:47
CSDN找的一个网页,照着抄练一次。
差不多的使用场景都在了。
package main import ( "fmt" ) type People interface { ReturnName() string } type Role interface { People ReturnRole() string } type Student struct { Name string } type Teacher struct { Name string } func (s Student) ReturnName() string { return s.Name } func (t *Teacher) ReturnName() string { return t.Name } func (s Student) ReturnRole() string { return "student" } func CheckPeople(test interface{}) { if _, ok := test.(People); ok { fmt.Println("Student implements People") } } func main() { cbs := Student{Name: "This is a student."} sss := Teacher{Name: "This is a teacher."} CheckPeople(cbs) var a People var b Role a = cbs name := a.ReturnName() fmt.Println(name) a = &sss name = a.ReturnName() fmt.Println(name) b = cbs role := b.ReturnRole() fmt.Println(role) Params := make([]interface{}, 3) Params[0] = 88 Params[1] = "This is a string" Params[2] = Student{Name: "cbs"} for index, v := range Params { if _, ok := v.(int); ok { fmt.Printf("Params[%d] is int type\n", index) } else if _, ok := v.(string); ok { fmt.Printf("Params[%d] is string type\n", index) } else if _, ok := v.(Student); ok { fmt.Printf("Params[%d] is custom Student type\n", index) } else { fmt.Printf("list[%d] unknown type.\n", index) } } for index, v := range Params { switch value := v.(type) { case int: fmt.Printf("Params[%d] is int type: %d\n", index, value) case string: fmt.Printf("Params[%d] is string type: %s\n", index, value) case Student: fmt.Printf("Params[%d] is custom Student type: %s\n", index, value) default: fmt.Printf("list[%d] unknown type.\n", index) } } }
输出:
D:/go-project/src/InterfaceGo/InterfaceGo.exe [D:/go-project/src/InterfaceGo] Student implements People This is a student. This is a teacher. student Params[0] is int type Params[1] is string type Params[2] is custom Student type Params[0] is int type: 88 Params[1] is string type: This is a string Params[2] is custom Student type: {cbs} 成功: 进程退出代码 0.
最新文章
- chrome浏览器调试typescript
- mongo virtual
- webpack实战
- FusionCharts参数的详细说明和功能特性(转)
- 剑指Offer:面试题17——合并两个排序的链表
- JavaScript探秘系列
- ios/mac/COCOA系列 -- UIALertVIew 学习笔记
- IsPostBack
- Python3实现连接SQLite数据库的方法
- coredata中谓词的使用
- WCF---服务发布的步骤
- 同时安装VS2010,VS2012
- Linux增加磁盘操作
- Spring中IOC和AOP的理解
- MySQL必知必会 前10章学习笔记
- 添加AD RMS role时,提示密码不能被验证The password could not be validated
- [洛谷U40581]树上统计treecnt
- MinGW 使用 mintty 终端替代默认终端以解决界面上复制与粘贴的问题
- (3.16)mysql基础深入——mysql字符集
- DQN(Deep Reiforcement Learning) 发展历程(五)
热门文章
- Lniux系统-Ubantu安装搜狗输入法
- CUDA 编程相关;tensorflow GPU 编程;关键知识点记录;CUDA 编译过程;NVCC
- CSRF说明
- Mybatis的动态sql以及分页
- leetcode 1041. 困于环中的机器人
- LG1345 「USACO5.4」Telecowmunication 最小割
- matlab练习程序(BRIEF描述子)
- __setattr__和__delattr__和__getattr__
- lua require路径设置实例
- Java13 闪亮来袭,你是否还停留在 Java8