当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > [Go] golang的接口合约

[Go] golang的接口合约

2019年02月22日  | 移动技术网IT编程  | 我要评论

接口类型
1.接口类型具体描述了一系列方法的集合,实现这些方法的具体类型是这个接口类型的实例
2.一个类型如果拥有一个接口需要的所有方法,那么这个类型就实现了这个接口

package main

import (
	"fmt"
)

//定义一个接口类型person
type person interface {
	//描述了一个需要实现的say方法,返回的类型是error
	say() error
}

//定义一个类型
type tsh struct{}

//给类型定义独占方法,参数返回值和person接口要求的一样,就意味着实现了该接口
func (t *tsh) say() error {
	fmt.println("我是tsh")
	return nil
}
func main() {
	//实例化
	tsh := tsh{}
	//直接调用实例的方法
	tsh.say()
	//该测试方法要求传入person类型,因为我的tsh实现了person接口,所以我的tsh也可以传入
	test(&tsh)

}

//测试方法要求传入person类型
func test(p person) {
	p.say()
}

 

  

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网