go语言实现虚函数功能

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>

目的是当前结构体实例可以用所有实现了该接口的其他结构体来初始化(即使他们的属性不完全一致)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值