let’s say I have the following struct:
struct Dog
name
age
end
then I wanted to create an array of dogs like the following:
array = [Dog(:Jack, 2), Dog(:Max, 3)]
2-element Vector{Dog}:
Dog(:Jack, 2)
Dog(:Max, 3)
is it possible to alias a struct with it’s field; in this case, the field “name” so that I would get something like this:
2-element Vector{Dog}:
:Jack
:Max
I don’t know what you mean by “alias” in this context, I presume you are not referring to accessing the name
field like this:
julia> struct Dog
name
age
end
julia> array = [Dog(:Jack, 2), Dog(:Max, 3)]
2-element Vector{Dog}:
Dog(:Jack, 2)
Dog(:Max, 3)
julia> getfield.(array, :name)
2-element Vector{Symbol}:
:Jack
:Max
?
1 Like
If what you mean by “alias” is to customize the way Dog
instances are printed, then you can define a new, specific method for Base.show
. This is explained in mode details in the Custom pretty-printing section of the manual
julia> struct Dog
name
age
end
julia> array = [Dog(:Jack, 2), Dog(:Max, 3)]
2-element Vector{Dog}:
Dog(:Jack, 2)
Dog(:Max, 3)
julia> function Base.show(io::IO, mime::MIME"text/plain", dog::Dog)
show(io, mime, dog.name)
end
julia> array
2-element Vector{Dog}:
:Jack
:Max
4 Likes
If I am going to create an array of structs with say 5, 10 fields, it would look ugly. That’s why I wanted to represent each struct with the field name.
thanks, that’s what I was looking for!