go没有虚函数,因此需要用这个来间接实现对派生对象函数的引用。
package main
import "fmt"
type dosomething interface {
printhello()
printworld()
printgood()
}
type innerStruct struct {
num int
//functions dosomething
}
func (i *innerStruct) printhello() {
fmt.Println("hello")
}
type outerStruct1 struct {
*innerStruct
}
func (o *outerStruct1) printworld() {
fmt.Println("world1")
}
type outerStruct2 struct {
*innerStruct
}
func (o *outerStruct2) printworld() {
fmt.Println("world2")
}
func main() {
outer1 := outerStruct1{&innerStruct{num:123}}
outer1.printhello()
outer1.printworld()
//outer1.functions = &outer1
outer2 := outerStruct2{&innerStruct{num:123}}
outer2.printhello()
outer2.printworld()
//outer2.functions = &outer2
}
/*
go没有虚函数,因此需要用这个来间接实现对派生对象函数的引用
不把interface放入结构体也是可以的
放入只是为了确保最终实现了所有函数
类似于虚函数,全部实现了那个类才能用
把它放进去,一层一层套用,最后实现了接口中所有函数,就可以用了
如果去掉上述代码中的注释,需要添加下列函数才行。
func (i *innerStruct) printgood() {
fmt.Println("good")
}
*/
输出:
hello
world1
hello
world2
其他参考:
结构体中嵌入接口的作用
golang的struct里面嵌入interface
来自 <https://www.jianshu.com/p/a5bc8add7c6e>
嵌入interface可以使得一个struct具有interface的接口,而不需要实现interface中的有声明的函数。
Go编程之接口作结构体属性
来自 <https://blog.csdn.net/star199207/article/details/79054583>
目的是当前结构体实例可以用所有实现了该接口的其他结构体来初始化(即使他们的属性不完全一致)