Understanding of mutable struct


#1

Suppose I define a mutable struc as follows:

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?

Carsten


#2

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.


#3

I’ve edited your post to quote the code, making it more readable. Please see

for details on how to quote your code yourself.


#4

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.


#5

I think you want:

julia> mutable struct Sp{T <: AbstractString}
          a::T
          b::T
          c::T
          d::T
       end

julia> sp = Sp("a1",
              "b1",
              "c1",
              "d1"
              )
Sp{String}("a1", "b1", "c1", "d1")