接口类型接管结构体
没有在接口中定义的函数而在结构体里新出现的函数,根据接口类型识别不到
type Interface1 interface {
Function1()
}
type Struct1 struct {
val string
}
func (struct1 *Struct1) Function1() {
fmt.Println(struct1.val)
}
func (struct1 *Struct1) Function2() {
fmt.Println("function2: ", struct1.val)
}
func main() {
var struct1 Interface1 = &Struct1{"val"}
struct1.Function1() //√
struct1.Function2() //not found
}
返回接口的用法
空接口类型interface{}可以表示任何类型
package main
import (
"fmt"
)
type Interface1 interface {
Function1()
}
type Struct1 struct {
str1 string
} //也可以是空结构体
// Struct1实现了Interface1接口
func (struct1 *Struct1) Function1() {
fmt.Println("struct1 function1, ", struct1.str1)
}
// 返回接口,实际上返回实现这个接口的结构体实例(或其指针)
func GetInterfaceFromStruct() (interface{}, error) {
//这里可以返回Struct1,也可以返回地址&Struct1
return &Struct1{
str1: "hello str1",
}, nil
}
func main() {
//接口类型接管结构体实例(常用于多态)
var struct1 Interface1 = &Struct1{"hello str1"}
struct1.Function1() //struct1 function1, hello str1
fmt.Printf("struct1 type: %T\n", struct1) //struct1 type: *main.Struct1
//结构体类型接管结构体实例(最常见用法)
struct2 := &Struct1{"hello str2"}
struct2.Function1() //struct1 function1, hello str2
fmt.Printf("struct2 type: %T\n", struct2) //struct2 type: *main.Struct1
//使用类型断言把空接口转换为具体类型
struct3, _ := GetInterfaceFromStruct()
fmt.Printf("struct3 type: %T\n", struct3) //struct3 type: *main.Struct1
//struct3.Function1() //not found
if struct4, ok := struct3.(*Struct1); ok {
fmt.Printf("struct4 type: %T\n", struct4) //struct4 type: *main.Struct1
struct4.Function1() //struct1 function1, hello str1
}
//类似于多态用法(接口类型接管结构体实例)
var interface1 Interface1
//interface1, _ = GetInterfaceFromStruct() //没办法直接赋值
//需要用类型
if interface2, ok := struct3.(*Struct1); ok {
interface1 = interface2
interface1.Function1() //struct1 function1, hello str1
}
}