Search code examples
crystal-lang

Why can't I change the value of self on Int32


If I try to implement an additional method, which doesn't change the value of self, on Int32 it works:

struct Int32
    def double
        self * 2
    end
end

x = Int32.new 2
p! x.double # => 4

However, as soon as I try to change self the compiler gives me an error, why? Is there a way to do this or is it completely impossible in Crystal?

struct Int32
    def six
        self = 6 # This fails
    end
end

I've also tried this on String and Char, I get the same compiler error: Error: can't change the value of self


Solution

  • Beta Ziliani's answer is good and looks at the bigger picture.

    For this particular example, the answer is actually very simple: primitive types in Crystal are immutable. So it's impossible to change the value of a primitive type's instance. Mutating methods always have to return a new value. That value can then be assigned to the same variable again.

    A workaround would be to wrap the primitive in a struct. Or as an unsafe alternative, you can pass a pointer to a variable with a primitive value to a method. Then the method can assign a value to that pointer.