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
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: