Closed lpegoraro closed 1 year ago
@lpegoraro Sorry for the delayed response. Yes, you're correct. Go doesn't enforce immutability within the values you set in the immutable
collections. If you make a change to a value, you should perform a copy of that value and set that new copy.
m := immutable.NewMap[string,int](nil)
// Set the initial value.
p := &Person{Name: "John", Age: 30}
m = m.Set("123", p)
// Make a copy and re-set the value.
other := *p
other.Age = 40
m = m.Set("123", &other)
So I was using this as a mock repository for my unit tests. And I figured it out that after storing them in the immutable map, the element that I stored, if I change it, I will still be able to change values inside it.
So for complete immutability, you would need that value to be copied within. maybe something like this?
https://go.dev/play/p/J5OJ-i7m0ue