接口

type Humaner interface {
	hello()
}
type Student struct {
	name string
	id   int
}
// 实现了Humaner
func (tmp *Student) hello() {
	fmt.Println(tmp.name, tmp.id)
}
func main() {
	// 实例化
	// f := new(Student)
	// f.name = "panghu"
	// f.id = 1
	// f.hello()

	f := Student{"panghu", 1}
	f.hello()
}

空接口

func main() {
	//空接口万能类型,保存任意类型的值
	var i interface{} = 1
	fmt.Println("i = ", i)

	i = "abc"
	fmt.Println("i = ", i)
}

接口继承

type Humaner interface {	// 子集
	hello()
}
type Personer interface {	// 超集
	Humaner // 匿名字段,继承了sayhi()
	sing(lrc string)
}
type Student struct {
	name string
	id   int
}

func (tmp *Student) hello() {
	fmt.Println(tmp.name, tmp.id)
}
func (tmp *Student) sing(lrc string) {
	fmt.Println("Student在唱着:", lrc)
}
func main() {
	s := Student{"panghu", 1}
	s.hello()
	s.sing("hello golang")
}

接口转换

type Humaner interface {	// 子集
	hello()
}
type Personer interface {	// 超集
	Humaner // 匿名字段,继承了sayhi()
	sing(lrc string)
}
type Student struct {
	name string
	id   int
}

func (tmp *Student) hello() {
	fmt.Println(tmp.name, tmp.id)
}
func (tmp *Student) sing(lrc string) {
	fmt.Println("Student在唱着:", lrc)
}
func main() {
	//超集可以转换为子集,反过来不可以
	var iPro Personer //超集
	iPro = &Student{"panghu", 18}
	iPro.hello()

	var i Humaner // 子集
	i = iPro // 超集可以转换为子集
	i.hello()
}

类型断言

type Student struct {
	name string
	id   int
}
func main() {
	i := make([]interface{}, 3)
	i[0] = 1                    //int
	i[1] = "hello go"           //string
	i[2] = Student{"mike", 666} //Student

	for _, v := range i {
		if value, ok := v.(int); ok == true {
			fmt.Println(value, ok)
		} else if value, ok := v.(string); ok == true {
			fmt.Println(value, ok)
		} else if value, ok := v.(Student); ok == true {
			fmt.Println(value, ok)
		}
	}
}

switch断言

type Student struct {
	name string
	id   int
}
func main() {
	i := make([]interface{}, 3)
	i[0] = 1                    //int
	i[1] = "hello go"           //string
	i[2] = Student{"mike", 666} //Student
	// 类型查询,类型断言
	for index, data := range i {
		switch value := data.(type) {
		case int:
			fmt.Printf("x[%d]类型为int, 内容为%d\n", index, value)
		case string:
			fmt.Printf("x[%d]类型为string, 内容为%s\n", index, value)
		case Student:
			fmt.Printf("x[%d]类型为Student, 内容为%s\n", index, value)	
		}
	}
}