1. 类和接口
go
type ClassName struct {}
type InterfaceName interface {}
- 结构体类型是值类型,接口类型是引用类型。
- interface{}类型的变量可以存储任何类型的值。我们使用interface.(type) 来检查 interface存储的值的实际类型,并根据类型执行不同的操作。
go
type MyType struct {
Value int
}
var client interface{} = MyType{Value: 42}
switch v := client.(type) { // v的值是MyType
case MyType:
fmt.Println("client is MyType, value:", v.Value)
case *MyType:
fmt.Println("client is *MyType, value:", v.Value)
default:
fmt.Println("client is of a different type")
}
2. 实现接口
go语言不会显示地声明实现了哪个接口,只要类实现了接口的所有方法,就隐式地实现了这个接口。
go
type Speaker interface { Speak() string }
type Person struct { name string }
func (p Person) Speak() string { return "Hello, my name is " + p.name }
3. 验证接口的实现
由于Go的接口是隐式实现的,所以无法明显知道某个结构体是否实现了接口的所以方法。
go
// 静态检查 *GobCodec结构体是否实现了 Codec接口的所有方法
// 若没有实现,编译时就会报错
var _ Codec = (*GobCodec)(nil) // 将nil转换为*GobCodec类型的指针并赋值给_