Hacker News new | past | comments | ask | show | jobs | submit login

Const typically prevents name rebinding (as the type system permits).

In C++ you can only call `const` methods through a const binding. `const` methods mark `this` const, so such methods cannot modify member variables. (Minus all escape hatches, such as `const_cast`.)

The author clearly knows this, [...] Immutability is the presumption that the whole data structure can't be mutated by default

The situation in Rust is a bit more complex. Rust distinguishes between interior and exterior mutability.

`let mut` bindings and `&mut` references exhibit exterior mutability - you can call methods that borrow `self` mutably (`&mut self`). Whereas `let` bindings and `&` references cannot. By the way, you can simply use moves to introduce exterior mutability for data that you own:

    let a = Vec::new();
    // Not allowed: a.push(1);
    
    // Move the vector.
    let mut b = a;
    b.push(1);
Even even if a data type uses an immutable binding or reference, it could still mutate that data structure if it has interior mutability (you just can't call methods that use self mutably). See the following small example, which uses an immutable binding to call a method that mutates the internal state of the struct.

https://play.rust-lang.org/?gist=6816dc9a03aca1e779f08443224...

The downside of interior mutability is that borrowing rules are enforced at run-time rather than compile-time.




C++ also has the `mutable` as a way to achieve something akin to internal mutability




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: