2 回答

TA貢獻1810條經驗 獲得超5個贊
我希望有效地擁有一些在所有方面都表現為 int 的東西,但有額外的方法。我希望能夠通過某種方式用它來代替 int。
目前在 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))
}

TA貢獻1853條經驗 獲得超9個贊
您可以基于 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
}
- 2 回答
- 0 關注
- 129 瀏覽
添加回答
舉報