Structs: Able to change members of type Vector{Float64}, but not of type Float64

Hello! :slight_smile:

When using an struct I am able to change the values inside members that are of type Vector, but I cannot not do it for members of type Float64. Do I need to change my struct to an immutable struct or is there a way around this? I would prefer not to use a mutable struct, since I need as much performance as possible. I have created an example below to illustrate my point.

#Initializing struct
struct test
    A::Float64
    B::Vector{Float64}
end

#Creating entry
example = test(1.0, [1.1, 1.2, 1.3])

#Changing a value in member B
example.B[2] = 5.0
println(example.B)

5.0

example.A = 2.0

ERROR: setfield!: immutable struct of type test cannot be changed
Stacktrace:
[1] setproperty!(x::test, f::Symbol, v::Float64)
@ Base .\Base.jl:43
[2] top-level scope
@ REPL[401]:1

you’re literally mutating your struct so you need mutable struct.

in example.B, it’s different because .B still points to the same vector, you’re mutating the vector, not example itself.

2 Likes

Okay I see thank you. I understand was is meant by mutable now. Have a nice day!

1 Like