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.

  

最新文章

  1. chrome浏览器调试typescript
  2. mongo virtual
  3. webpack实战
  4. FusionCharts参数的详细说明和功能特性(转)
  5. 剑指Offer:面试题17——合并两个排序的链表
  6. JavaScript探秘系列
  7. ios/mac/COCOA系列 -- UIALertVIew 学习笔记
  8. IsPostBack
  9. Python3实现连接SQLite数据库的方法
  10. coredata中谓词的使用
  11. WCF---服务发布的步骤
  12. 同时安装VS2010,VS2012
  13. Linux增加磁盘操作
  14. Spring中IOC和AOP的理解
  15. MySQL必知必会 前10章学习笔记
  16. 添加AD RMS role时,提示密码不能被验证The password could not be validated
  17. [洛谷U40581]树上统计treecnt
  18. MinGW 使用 mintty 终端替代默认终端以解决界面上复制与粘贴的问题
  19. (3.16)mysql基础深入——mysql字符集
  20. DQN(Deep Reiforcement Learning) 发展历程(五)

热门文章

  1. Lniux系统-Ubantu安装搜狗输入法
  2. CUDA 编程相关;tensorflow GPU 编程;关键知识点记录;CUDA 编译过程;NVCC
  3. CSRF说明
  4. Mybatis的动态sql以及分页
  5. leetcode 1041. 困于环中的机器人
  6. LG1345 「USACO5.4」Telecowmunication 最小割
  7. matlab练习程序(BRIEF描述子)
  8. __setattr__和__delattr__和__getattr__
  9. lua require路径设置实例
  10. Java13 闪亮来袭,你是否还停留在 Java8