Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> but I keep running up against the "immutable variable" problem

...Is that not what mut is for? I'm a bit confused what you're talking about here.



I don't really get immutable variables, or why you'd want to make copies of things so now you've got an updated variable and an out-of-date variable. Isn't that just asking for bugs?


As with many things, it comes down to tradeoffs. Immutable variables have one set of characteristics/benefits/drawbacks, and mutable variables have another. Different people will prefer one over the other, different scenarios will favor one over the other, and that's expected.

That being said, off the top of my head I think immutability is typically seen to have two primary benefits:

- No "spooky action at a distance" is probably the biggest draw. Immutability means no surprises due to something else you didn't expect mutating something out from under you. This is particularly relevant in larger codebases/teams and when sharing stuff in concurrent/parallel code.

- Potential performance benefits. Immutable objects can be shared freely. Safe subviews are cheap to make. You can skip making defensive copies. There are some interesting data structures which rely on their elements being immutable (e.g., persistent data structures). Lazy evaluation is more feasible. So on and so forth.

Rust is far from the first language to encourage immutability to the extent it does - making immutable objects has been a recommendation in Java for over two decades at this point, for example, to say nothing of its use of immutable strings from the start, and functional programming languages have been working with it even longer. Rust also has one nice thing as well which helps address this concern:

> or why you'd want to make copies of things so now you've got an updated variable and an out-of-date variable

The best way to avoid this in Rust (and other languages with similarly capable type systems) is to take advantage of how Rust's move semantics work to make the old value inaccessible after it's consumed. This completely eliminates the possibility that the old values anre accidentally used. Lints that catch unused values provide additional guardrails.

Obviously this isn't a universally applicable technique, but it's a nice tool in the toolbox.

In the end, though, it's a tradeoff, as I said. It's still possible to accidentally use old values, but the Rust devs (and the community in general, I think) seem to have concluded that the benefits outweigh the drawbacks, especially since immutability is just a default rather than a hard rule.




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

Search: