Go 多态功能实现

Go 多态功能实现

Go本身不具有多态的特性,不能够像Java、C++那样编写多态类、多态方法。但是,使用Go可以编写具有多态功能的类绑定的方法。为什么这么说呢?因为Go使用struct构建类,根据不同类调用不同的方法。下面将展示如何使用Go编写多态功能。

package main

import (
    "fmt"
)

type strCase struct{}

type intCase struct{}

func (text strCase) Add(x string, y string) string {
    return x + y
}

func (number intCase) Add(x int, y int) int {
    return x + y
}

func StartPolymorphism() {
    number := new(intCase)
    fmt.Print(" intCase Add: ", number.Add(1, 3), "\n")

    text := new(strCase)
    fmt.Print("strCase Add: ", text.Add("Add A", "Add B"), "\n")
}

func main(){
    StartPolymorphism()
}

输出结果:

intCase Add: 4
strCase Add: Add AAdd B

使用struct对象类型来消除了方法的模糊性。Go没法像Java语言那样直接写 泛型类或者泛型方法。Go具有它独有的语言特性,主要是为实现高并发而生。


欢迎加入我的微信公众号
欢迎加入我的微信公众号

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值