1:声明struct需要实现的方法
type aaa interface {//interface只能书写待实现的方法,及其需要
test()//继承该接口需要实现的方法
}
type ddd struct {
aaa//声明需要所属的interface接口
}
type bbb struct {
ddd//声明继承的结构体
}
func (this *bbb)ccc() {
fmt.Println(111)
}
//func (this *bbb)test() {
// fmt.Println(2222)
//}
func main() {
test := new(bbb)
test.test()
}
type testImplement struct {
S interface{//匿名接口作成员变量
Test()
}
}
2:通过断言,输出相应数据
针对interface时可以采用类型断言写法:
x.(T)
其中x为interface{}类型 T是要断言的类型
类型断言有个非常好的使用场景:当某个类型为interface{}的变量,真实类型为A时,才做某件事时,这时可以使用类型断言
另外x.(type)只能在switch中使用:
func MyPrintf(args ...interface{}) {
for _, arg := range args {
switch arg.(type) {
case int:
fmt.Println(arg, "is an int value.")
case string:
fmt.Println(arg, "is a string value.")
case int64:
fmt.Println(arg, "is an int64 value.")
default:
fmt.Println(arg, "is an unknown type.")
}
}
}
3:存储复杂的结构
test := new(bbb)//bbb为结构体
structList := make(map[string]interface{})
structList["test"] = test
for _, v := range structList {
f := v.(*bbb)//断言为对应的变量
f.test()
}
或者:
test := new(bbb)
structList := make(map[string]*bbb)
structList["test"] = test
for _, v := range structList {
v.test()
}