如何仅使用结构中的一个属性作为默认属性?
我想创建一个具有许多属性的结构,但在应用函数时,我希望它的行为就像其类型是选定的属性之一,例如:
mutable struct Field{T}
field_type::T
field_description::String
end
如果我为它分配一个String,在执行 print(Field{String}("Hello", "World"))
时,如果字段类型是 Int8,我希望它打印
我希望能够做到Hello
Field{Int8}(1, "First term") + Field{Int8}(1,"Second term")
并得到 2
等等。这有可能吗?
对于更多上下文,我希望将一些元数据添加到字段类型,但它必须表现为所选的 field_type
I want to create a struct with many properties, but when applying the functions, I want it to behave like its type is one of the selected properties, for example:
mutable struct Field{T}
field_type::T
field_description::String
end
I want this struct to behave as the T type, if I assign it a String, when doing print(Field{String}("Hello", "World"))
I want it to print Hello
, if field type is a Int8
I want to be able to do Field{Int8}(1, "First term") + Field{Int8}(1,"Second term")
and get 2
and so on. Is this possible somehow?
For more context, I want this to add some metadata to the Field Type, but it has to behave as the chosen field_type
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你把事情搞得太复杂了。您只需要认识到
Field{String}
和Field{Int8}
是两种不同的类型,并将它们视为不同的类型。例如:
因此,对于打印和添加,请定义:
您可以通过定义来使其更加通用
。
我定义了
show
而不是 print,因为这样更方便,但您可以为任何您喜欢的Field{T}
定义任何方法。只需记住不同的T
会给出不同的类型,这很简单。我建议您创建另一个便利构造函数:
现在您不需要在构造函数调用中指定
T
:You are over-complicating things. You just need to realize that
Field{String}
andField{Int8}
are two separate types, and treat them as such.For example:
So for printing and adding, define:
You could make it more generic by defining
instead.
I defined
show
instead of print, since that is more convenient, but you can define any methods for anyField{T}
that you like. Just remember that differentT
gives different types, and it's easy.I would recomment that you create another convenience constructor:
Now you don't need to specify
T
in the constructor call:我会考虑使用
Base.@kwdef
或Parameters
包中更好的等效项。现在:
或:
现在:
但是,如果您不想提供名称,您可以这样做:
现在您可以这样做:
I would consider using
Base.@kwdef
or a better equivalent in theParameters
package.And now:
or:
And now:
However if you do not want to provide the name you can do:
And now you can just do: