英文:
How to define type without operations allowed on the underlying type?
问题
如果我定义了一个类型定义:
type X int64
为什么我可以这样做:
var x X = 123
x = x + 1
x
的行为就像它是底层的 int64
类型一样,而我并不希望如此。或者说它允许在这个新类型上执行底层类型的操作?
我定义一个新类型的原因之一是为了隐藏底层类型并在其上定义自己的操作。
英文:
If I define a type definition
type X int64
Why is it that I can then do
var x X = 123
x = x + 1
The x
behaves as if it was the underlying int64
, which I don't want. Or that it allows operations on the underlying type to be performed on this new type?
One of the reasons I'd define a new type is to hide the underlying type and define my own operations on it.
答案1
得分: 4
创建一个新的定义类型将解除与底层类型的任何方法的关联,但它不会解除与运算符(如+ - / *
)的功能关联。
> 一个定义类型可以有与之关联的方法。它不会继承与给定类型绑定的任何方法。
你应该基于一个具有所需运算符的底层类型来定义你的类型。例如,如果你不想要算术运算符,你可以从一个struct
派生。
如果你的类型出于内部原因仍然需要int64
的算术能力,你可以将其隐藏为结构体中的一个未导出字段。例如:
type X struct {
number int64
}
英文:
Creating a new defined type will dissociate any methods on the underlying type, but it does not dissociate functionality with operators such as + - / *
.
> A defined type may have methods associated with it. It does not inherit any methods bound to the given type
You should base your type on an underlying type with the desirable operators. For example, if you don't want to have arithmetic operators, you can derive from a struct
.
If your type still needs the arithmetic capabilities of an int64
for internal reasons, you can hide it as an un-exported field in the struct. For example:
type X struct {
number int64
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论