go模拟类的继承

本文详细介绍了Golang中如何通过结构体和方法实现面向对象编程,包括代码重用、方法覆盖及多态特性,展示了Go语言虽无传统类概念,但仍能实现类似面向对象的功能。

 

golang没有类,只有struct,但也可以做到类的效果,如:

type Animal struct {
	Name   string
	Weight string
}

func (a *Animal) Eat(food string) {
	fmt.Printf("%s eat some food %s\n", a.Name, food)
}

go使用组合的形式实现了代码重用,当一个结构体包含了另一个结构体,那么外面的结构体就拥有里面结构体的所有成员变量和 方法 ,这就有点类似于继承了:


type Bird struct {
	Animal
}

func (b *Bird) Fly() {
	fmt.Println("I'm flying")
}

func (b *Bird) Eat(food string) {
	fmt.Println("bird eat...")
}

Bird有Animal的一切属性和方法,还有自己的方法,并覆盖了父类的方法Eat,再看如何调用:

func main() {
	var b Bird
	b.Name = "bird"
	b.Eat("nut")
	b.Animal.Eat("leaf")
}

输出:

bird eat...
bird eat some food leaf

可见Bird覆盖了父类方法,如要调用父类方法,则需这样调用b.Animal.Eat("leaf")。可以把Bird的Eat方法参数去掉:

func (b *Bird) Eat() {
	fmt.Println("bird eat...")
}

有点重载的味道了。

 

能否继承其他包的struct,并覆盖它的方法呢?

base.go代码:

package base

import "fmt"

type Base struct {
	Name string
}

func (b *Base) Print() {
	fmt.Println("this is base class print")
}

 

再“继承”和覆盖父类方法,

type Child struct {
	base.Base
}

func (c *Child) Print() {
	fmt.Println("this is child class print")
}

调用:

func main() {
	c := Child{}
	c.Base.Print()
	c.Print()
}

输出:

this is base class print
this is child class print

可见是一样的。

go虽然没有类的概念,可是也有面向对象的元素和方式,继承、封装、多态,都齐全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值