4 ms·
> In Rust you... can't do that because they'd all need to be read-only? Here's one way to think of it: There's the kind of code that Rust "wants" you to write,
by ekidd 9y ago
> In Rust you... can't do that because they'd all need to be read-only?
Here's one way to think of it: There's the kind of code that Rust "wants" you to write, and then there's the kind of code that it allows to write.
Rust "wants":
- Lots of immutable data, with relatively sparing use of mutability.
- Clear ownership and borrowing.
Rust allows:
- Pretty much anything you could write in C, with the possible exception of bitfields in structs. You wanna directly access the pic8259 chip from kernel space? Have fun: https://github.com/emk/toyos-rs/blob/fdc5fb8cc8152a63d1b6c85cd357737e6b1aebb5/crates/pic8259_simple/src/lib.rs https://github.com/emk/toyos-rs/blob/fdc5fb8cc8152a63d1b6c85...
The question is, is it worth exercising that full power for "ordinary" Rust code? To use your example, if you have a data structure D and a view V, can you reach "through" V and mutate the underlying D? Of course you can do this, if you really need to. You have lots of choices, including (for example) cells, locks, tricky lifetime annotations and/or unsafe code.
But in practice, it's usually not worth the hassle. What I do in a case like this is step back and ask myself, "How would I solve this problem in a functional language like Clojure, ML or Haskell?" Oftentimes, that will give me a nice, simple solution that Rust likes. But sometimes I actually do need to do things the hard way.
Part of being happy in Rust is learning how to minimize the use of mutable data. For example, if you're writing a video game and you need to update your "world state", do you really need to mutate the existing state? Or can you write a function that takes the old world state and the player's input, and uses them to compute a brand new world state? The latter actually eliminates all kinds of subtle bugs, and it can be done efficiently.