Go 学习之接口 (三)
定义
1、定义
Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。
type example interface{
Method1(参数列表) 返回值列表
Method2(参数列表) 返回值列表
…
}
2、interface类型默认是一个指针
type example interface{
Method1(参数列表) 返回值列表
Method2(参数列表) 返回值列表
…
}
var a example
a.Method1()
3、接口实现
- a. Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement类似的关键字。
- b. 如果一个变量含有了多个
interface类型的方法,那么这个变量就实现了多个接口。 - c. 如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现这个接口。
示例:
package main
import "fmt"
type Carer interface {
GetName() string
Run()
DiDi()
}
type BMW struct {
Name string
}
func (p *BMW) GetName() string {
return p.Name
}
func (p *BMW) Run(){
fmt.Printf("%s is running", p.Name)
}
func (p *BMW) DiDi() {
fmt.Printf("%s is didi", p.Name)
}
func main() {
var car Carer
fmt.Println(car)
var bmw BMW
bmw.Name = "BMW"
car = &bmw
car.Run()
}
结果:
<nil>
BMW is running
Process finished with exit code 0
4、多态
一种事物的多种形态,都可以按照统一的接口进行操作。
5、 接口嵌套
一个接口可以嵌套在另外的接口,如下所示:
type ReadWrite interface {
Read(b Buffer) bool
Write(b Buffer) bool
}
type Lock interface {
Lock()
Unlock()
}
type File interface {
ReadWrite
Lock
Close()
}
6、类型断言
由于接口是一般类型,不知道具体类型,如果要转成具体类型

练习
写一个函数判断传入参数的类型
func classifier(items ...interface{}) {
for i, x := range items {
switch x.(type) {
case bool: fmt.Printf(“param #%d is a bool\n”, i)
case float64: fmt.Printf(“param #%d is a float64\n”, i)
case int, int64: fmt.Printf(“param #%d is an int\n”, i)
case nil: fmt.Printf(“param #%d is nil\n”, i)
case string: fmt.Printf(“param #%d is a string\n”, i)
default: fmt.Printf(“param #%d’s type is unknown\n”, i)
}
}
为者常成,行者常至
自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)