go interface
Interface 基本使用
// _Interfaces_ are named collections of method
// signatures.
package main
import "fmt"
import "math"
// Here's a basic interface for geometric shapes.
type geometry interface {
area() float64
perim() float64
}
// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
width, height float64
}
type circle struct {
radius float64
}
// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
// The implementation for `circle`s.
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main() {
r := rect{width: 3, height: 4}
c := circle{radius: 5}
// The `circle` and `rect` struct types both
// implement the `geometry` interface so we can use
// instances of
// these structs as arguments to `measure`.
measure(r)
measure(c)
}
这个例子的官方解释是:
矩形和圆形都实现了几何图形的接口
我来做几点解释:
- measure 的参数是一个 geometry 的接口(interface)
- 当调用 measure 函数的时候会有一次类型转换,将实参转换为形参接口类型
- 这个转换过程是在编译期间完成的,编译器会检测方法列表,当实参方法列表是形参方法列表的超集时,此次转换成功
空 Interface
上面那个例子是有方法的interface作为参数,但是很多时候还会出现一种空interface
空interface(interface{})不包含任何的method,因此所有的类型都实现了空interface。
因此空Interface就很像C语言里面的空指针。
但是不同的是,接口包含的是方法。并且空接口也不是直接强制转换为其他接口的,而是通过如下方法:
func Disconnect(usb interface{}){ //注意,这里是空接口
switch v:=usb.(type) {
case PhoneConnect:
fmt.Println(" Phone device Disconnected from",v.name)
case TVConnect:
fmt.Println("TV device Disconnected from",v.name)
default:
fmt.Println("Unknown device ...")
}
}
func main(){
a := PhoneConnect{"IPhone"}
b := TVConnect{"ChuangWei"}
Disconnect(a)
Disconnect(b)
}
这种方式被称为Comma-ok断言
Comma-ok断言的语法是:value, ok := element.(T)。element必须是接口类型的变量,T是普通类型
如果element是T类型的数据,那么断言成功,转换为value对象。否则OK被置为false
还有一种switch语法就如同上面例子中使用的一样
参考链接: