mutable struct Np <: Number
a::Float64
b::Int
c::ComplexF64
d::Float64
end
Assigning numerical values:
np = Np(1.2,
3,
1+4im,
3
);
which results in:
> julia> np
Np(1.2, 3, 1.0 + 4.0im, 3.0)
This is what I expected. Doing the same with strings:
mutable struct Sp <: AbstractString
a::String
b::String
c::String
d::String
end
Again, assinging values:
> julia> sp = Sp("a1",
"b1",
"c1",
"d1"
);
with no error message. Bur when I try to show the single elements (as I did above for np) I’ve got the error message:
"Error showing value of type Sp:
ERROR: MethodError: no method matching iterate(::Sp)
Closest candidates are:
iterate(::AbstractString, ::Integer) at strings/basic.jl:135
iterate(::Core.SimpleVector) at essentials.jl:589
iterate(::Core.SimpleVector, ::Any) at essentials.jl:589
However, the single elements are accessible:
julia> sp.a
"a1"
Is there a specific reason why string types in structures behave different compared to number types?
When you do Sp <: AbstractString you will opt in to using the AbstractString methods already defined. show on an AbstractString tries to iterate it and show the characters in it. This fails for your type since it doesn’t provide iteration.
Also note that you probably don’t want Np <: Number either—it means that Np is a kind of number just like Sp <: AbstractString means that Sp is a kind of string. It has nothing to do with the types of the fields of these structures, which can be anything.