猿问

如何通过扩展类型向 int 等基本类型添加功能?

我希望能够向现有类型(例如 int)添加方法:


func (i *int) myfunction {

   ...

}

然而,这显然会产生错误。


无法在非本地类型上定义新方法


谷歌的顶部结果是一个针对 golang 的github 问题。有希望的是,答案是您已经可以通过其他方式获得此功能,因此他们不会对语言进行此更改。


无济于事的是,回复含糊不清


type extended Existing

并且它没有明确显示如何实现OP的要求,即:


func (a int) sum(b int) (total int) {

    total = a + b

    return

}

那么,如何扩展 int 来添加功能呢?还可以像 int 一样使用吗?如果是这样,怎么办?


我希望有效地拥有一些在所有方面都表现为 int 的东西,但有额外的方法。我希望能够通过某种方式用它来代替 int。


守着星空守着你
浏览 99回答 2
2回答

森栏

我希望有效地拥有一些在所有方面都表现为 int 的东西,但有额外的方法。我希望能够通过某种方式用它来代替 int。目前在 Go 中这是不可能的,因为它不支持任何类型的泛型。您可以实现的最佳效果如下:package maintype Integer intfunc (i Integer) Add(x Integer) Integer {    return Integer(int(i) + int(x))}func AddInt(x, y int) int {    return x + y}func main() {    x := Integer(1)    y := Integer(2)    z := 3    x.Add(y)    x.Add(Integer(z))    x.Add(Integer(9))    # But this will not compile    x.Add(3)    # You can convert back to int    AddInt(int(x), int(y))}

暮色呼如

您可以基于 int 声明一个新类型,并使用它:type newint intfunc (n newint) f() {}func intFunc(i int) {}func main() {   var i, j newint    i = 1    j = 2    a := i+j  // a is of type newint    i.f()    intFunc(int(i)) // You have to convert to int}
随时随地看视频慕课网APP

相关分类

Go
我要回答