1. interface:简单的说,interface是一组method的组合,我们通过interface来定义对象的一组行为。
参考下面这个例子:
package main
import "fmt"
type Human interface {
speak(language string)
}
type Chinese struct {
}
type American struct {
}
func (ch Chinese) speak(language string ) {
fmt.Printf("speck %s\n",language)
}
func (am American ) speak(language string ) {
fmt.Printf("speck %s\n",language)
}
func main() {
var ch Human
var am Human
ch = Chinese{}
am = American{}
ch.speak("Chinese")
am.speak("English")
}
2. 空interface
3.interface变量存储的类型
package main
import (
"fmt"
"strconv"
)
type Element interface{}
type List [] Element
type Person struct {
name string
age int
}
//打印
func (p Person) String() string {
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
}
func main() {
list := make(List, 3)
list[0] = 1 //an int
list[1] = "Hello" //a string
list[2] = Person{"Dennis", 70}
for index, element := range list{
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
default:
fmt.Println("list[%d] is of a different type", index)
}
}
需要注意:element.(type)语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用comma-ok