如何通过扩展类型向 int 这样的基本类型添加功能?
How do I add functionality to a basic type like int by extending the type?
我希望能够向现有类型(例如 int)添加方法:
func (i *int) myfunction {
...
}
但是,这显然会产生错误。
cannot define new methods on non-local type
最高 google 结果是针对 golang 的 github issue 开局。令人欣慰的是,答案是您已经可以通过其他方式获得此功能,因此他们不会对语言进行此更改。
毫无帮助,回复含糊不清
type extended Existing
并且它没有明确显示如何实现 OP 所要求的,即:
func (a int) sum(b int) (total int) {
total = a + b
return
}
那么,如何扩展一个 int 来添加功能呢?它仍然可以像 int 一样使用吗?如果是这样,如何?
我想要有效地拥有在所有方面都像 int 一样运行的东西,但有额外的方法。我希望能够通过某种方式以各种方式使用它代替 int。
I would like to effectively have something that behaves in all ways as an int, but has additional methods. I would like to be able to use this in place of an int in all ways by some means.
目前在 Go 中这是不可能的,因为它不支持任何类型的泛型。
你能达到的最好结果如下:
package main
type Integer int
func (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 int
func (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
}
我希望能够向现有类型(例如 int)添加方法:
func (i *int) myfunction {
...
}
但是,这显然会产生错误。
cannot define new methods on non-local type
最高 google 结果是针对 golang 的 github issue 开局。令人欣慰的是,答案是您已经可以通过其他方式获得此功能,因此他们不会对语言进行此更改。
毫无帮助,回复含糊不清
type extended Existing
并且它没有明确显示如何实现 OP 所要求的,即:
func (a int) sum(b int) (total int) {
total = a + b
return
}
那么,如何扩展一个 int 来添加功能呢?它仍然可以像 int 一样使用吗?如果是这样,如何?
我想要有效地拥有在所有方面都像 int 一样运行的东西,但有额外的方法。我希望能够通过某种方式以各种方式使用它代替 int。
I would like to effectively have something that behaves in all ways as an int, but has additional methods. I would like to be able to use this in place of an int in all ways by some means.
目前在 Go 中这是不可能的,因为它不支持任何类型的泛型。
你能达到的最好结果如下:
package main
type Integer int
func (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 int
func (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
}