一、接口Interface
接口是一种特殊的类型,抽象类型。
1.定义
/*
type 接口名 interface{
方法名1(参数1, 参数2...)(返回值1, 返回值2...)
方法名2(参数1, 参数2...)(返回值1, 返回值2...)
...
}
*/
//定义runer接口
type runer interface {
run()
}
//定义eater接口
type eater interface {
eat(string)
}
2.实现
//定义dog类型
type dog struct {
name string //动物名称
}
//定义person类型
type person struct {
name string //姓名
}
//给dog类实现run接口
func (a *dog) run() {
fmt.Printf("%s正在跑...\n", a.name)
}
//给dog类实现eat接口
func (a *dog) eat(food string) {
fmt.Printf("%s正在吃%s...\n", a.name, food)
}
//给person类实现run接口
func (p *person) run() {
fmt.Printf("%s正在跑...\n", p.name)
}
//给person类实现eat接口
func (p *person) eat(food string) {
fmt.Printf("%s正在吃%s...\n", p.name, food)
}
3.使用
//测试runer接口
func test_runer(r runer) {
r.run()
}
//测试eater接口
func test_eater(food string, e eater) {
e.eat(food)
}
func main() {
var a dog
a.name = "哈士奇"
var p person
p.name = "张三"
//test_runer可以接收dog和person两种类型
test_runer(&a)
test_runer(&p)
//test_eater可以接收dog和person两种类型
test_eater("骨头", &a)
test_eater("披萨", &p)
}
输出:
哈士奇正在跑...
张三正在跑...
哈士奇正在吃骨头...
张三正在吃披萨...
二、接口嵌套
1.定义
type animal interface {
runer
eater
}
//定义runer接口
type runer interface {
run()
}
//定义eater接口
type eater interface {
eat(string)
}
2.使用
//测试animal接口
func test_animal(food string, a animal) {
a.run()
a.eat(food)
}
func main() {
var a dog
a.name = "哈士奇"
var p person
p.name = "张三"
//animal可以接收dog和person两种类型
test_animal("骨头", &a)
test_animal("披萨", &p)
}
输出:
哈士奇正在跑...
哈士奇正在吃骨头...
张三正在跑...
张三正在吃披萨...
三、空接口
1.定义
interface{} //空接口
2.使用
func main() {
var m map[int]interface{}
m = make(map[int]interface{}, 1)
m[1] = "哈士奇"
m[2] = 5000
m[3] = true
m[4] = [...]int{0, 1, 2, 3, 4, 5, 6}
fmt.Println(m) //map[1:哈士奇 2:5000 3:true 4:[0 1 2 3 4 5 6]]
}
3.类型断言
func assign(i interface{}) {
fmt.Printf("type:%T\n", i)
switch i.(type) {
case string:
fmt.Println("this is a string.")
case bool:
fmt.Println("this is a boolean.")
case int:
fmt.Println("this is a int.")
case int64:
fmt.Println("this is a int64.")
default:
fmt.Println("this is unknow type.")
}
}
func main() {
assign(10)
assign("哈士奇")
assign("true")
}
本文探讨了接口在编程中的关键概念,包括接口的定义、实现以及如何通过接口进行类型测试。重点介绍了接口嵌套和空接口的使用,实例演示了如何让不同类型(如Dog和Person)通过统一接口进行操作。
217

被折叠的 条评论
为什么被折叠?



