博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go基础知识学习(6) 接口
阅读量:6985 次
发布时间:2019-06-27

本文共 2100 字,大约阅读时间需要 7 分钟。

hot3.png

Golang接口定义使用interface来声明,它相对于其他语言最大的特定就是接口定义和实现的关联性仅仅依赖接口的名字和声明,无需显式声明。

  1. 接口定义和实现 在下面这个例子中,定义了两个自定义类型city country 和接口类型IName city、country分别实现了接口IName, 它们不需要代码上不需要去和IName关联(比如implement IName),只需要实现 IName定义的方法即可。接口更像是双方约定的协议,达到更加精炼、灵活的效果。

  2. 空接口:interface{} 它不包含任何的方法,所以类型都实现了空接口。空接口在我们需要存储任意类型的时候相当有用,非常类似C语言中void* 类型。printname 函数中输入参数就是一个空接口

  3. 接口检查 有时候需要检查某个obj是否实现了接口,可以用obj.(I)来查询它是否实现了接口 printname中 ivalue, ok := p.(IName) if !ok { fmt.Println("It is not a IName interface obj:", p) return }

  4. 接口类型 由于实现接口的obj可能有多个,如果需要确切知道是哪一个,可以使用 obj.(type)来判断。 这里有两个实现IName接口的struct, printname 中就是通过obj.(type) 来判断是city 还是country.

Code:

package mainimport (	"fmt")type city struct {	name string}func (c city) Put(name string) {	c.name = name}func (c city) GetName() string {	return c.name}type country struct {	name string}func (c country) Put(name string) {	c.name = name}func (c country) GetName() string {	return c.name}type IName interface {	Put(string)	GetName() string}//interface type and queryfunc printname(p interface{}) {	ivalue, ok := p.(IName)	if !ok {		fmt.Println("It is not a IName interface obj:", p)		return	}	switch ivalue.(type) {	case *city:		fmt.Println("It is a *city: ", ivalue.GetName())	case *country:		fmt.Println("It is a *country: ", ivalue.GetName())	case city:		fmt.Println("It is a city: ", ivalue.GetName())	case country:		fmt.Println("It is a country: ", ivalue.GetName())	default:		fmt.Println("It is other IName interface")	}}func main() {	var c1, c2, c3, c4 interface{}	c1 = city{name: "Hangzhou"}	c2 = country{name: "US"}	c3 = &city{name: "Shanghai"}	c4 = &country{name: "Japan"}	fmt.Println(c1)	fmt.Println(c2)	fmt.Println(c3)	fmt.Println(c4)	//print name of object has interface IName	printname(c1)	printname(c2)	printname(c3)	printname(c4)	//print name of object not has interface IName	printname(10)	printname("abc")}

Output:

{Hangzhou}{US}&{Shanghai}&{Japan}It is a city:  HangzhouIt is a country:  USIt is a *city:  ShanghaiIt is a *country:  JapanIt is not a IName interface obj: 10It is not a IName interface obj: abc

code :

转载于:https://my.oschina.net/panyingyun/blog/300007

你可能感兴趣的文章
递归增量监控目录/文件,逐行读取内容并输出
查看>>
CHAR和VARCHAR
查看>>
GIT分支创建和合并
查看>>
FreeBSD9.0 安装php-fpm
查看>>
MapXtreme 2005 学习心得 相关代码知识(三)
查看>>
CSS 字体系列
查看>>
[M0]Android开启odex,优化开机速度
查看>>
transfer.sh:通过命令行简单的创建文件分享
查看>>
java 远程debug
查看>>
高德地图POI查找
查看>>
Java transient关键字
查看>>
磁盘格式化
查看>>
Mybatis 在 insert 之后想获取自增的主键 id,但是总是返回1
查看>>
遭遇各种内容监管,有些企业到底欠缺的是什么,仅仅是价值观吗?
查看>>
华为交换机重置密码
查看>>
CentOS 7安装KVM虚拟机OpenSUSE42操作实录
查看>>
专属小白们的Zabbix部署详解
查看>>
shareinstall可以解决地推统计这个难题
查看>>
Mac Mysql Access denied for user 'root'@'localhost
查看>>
Python学习三级菜单
查看>>