this is an odd problem I have been having. Essentially, I am inadvertently changing the value of a field of an immutable struct and I have no idea how! I have created a reproducible problem, although it is a bit long, so please bear with.
Suppose we have a vector of points, and we wish to swap the first element of the vector with a new point. We create a swap_first
type which stores the vector of original points and the new point.
struct Point
x::Float64
y::Float64
end
struct swap_first
orig_points::Vector{Point}
new_point::Point
end
Then, creating some points and a function which swaps the first point with the new point:
p1=Point(1,2);
p2=Point(3,4);
orig=[p1,p2];
newp=Point(10,11);
swap_object=swap_first(orig,newp);
function func_swap(val::swap_first)
new_p=val.orig_points;
new_p[1]=val.new_point;
return new_p
end
func_swap(swap_object);
And somehow, applying this function which creates a new vector of points without touching the original object, we have changed the value of the field orig_points
of the variable swap_object
.
println(swap_object.orig_points)
Point[Point(10.0, 11.0), Point(3.0, 4.0)]
The original elements of the vector were [Point(1,2),Point(3,4)]
. I want to keep the original value of swap_object, as well as have the new vector of points! I thought changing fields of an immmutable struct wasn't possible because of the immutability of structs! Help on this would be greatly appreciated. Thanks for reading.