Hacker News new | ask | show | jobs
by kibwen 3695 days ago
String literals in Rust produce references to data living in static memory. The `String` type, which is dynamically-allocated and growable, is only created when requested due to the cost of dynamic allocation.
1 comments

So, do you need to convert the string to a string whenever you want to use a mutable string?
If you have a string slice (&str) you need to convert it to a String you own before you can mutate it, yes. In some other languages strings are always immutable, and mutating them requires creating a copy. In Rust if you own the memory (and haven't given out any immutable references to anyone), you can mutate it.

String literals are an interesting case for the reason mentioned in the earlier comment: they reference memory that no code "owns", as in-place mutation of the executable would be unsafe.

Some languages have mutable strings but these are usually unsafe if used concurrently, or require locks. In Rust this is modeled in the type/borrow system.

> In some other languages strings are always immutable, and mutating them requires creating a copy.

Those languages used to introduce mutable wrappers and not a "to_string()" method.

> they reference memory that no code "owns", as in-place mutation of the executable would be unsafe.

Is that similar to the dynamics of uniqueness types?

> Those languages used to introduce mutable wrappers and not a "to_string()" method.

Yes! This is similar to, say, StringBuilder in Java. The difference is that ownership is intertwined with the type here. Strings are always owned, and as such you can choose to mutate them. String slices (references) are not owned by you (you borrow them), so you can't do anything that would be memory unsafe. You can borrow a mutable slice of the String (like a reference to the backing array), which you can alter in-place but you cannot do anything that would require reallocation (Strings being growable was mentioned earlier -- mutable slices are not). Slices which come from string literals are always immutable.

For probably-obvious reasons you can only take one mutable reference at once, while you can have as many immutable references as you like. Taking a mutable reference also prevents you taking any immutable references at the same time: https://doc.rust-lang.org/book/references-and-borrowing.html...

In my own experience this takes a bit of time to get used to, and in some cases the rules are still quite frustrating. People with more experience of the language report that they get used to it, though.

> Is that similar to the dynamics of uniqueness types?

I believe it's similar, but I'm not super-familiar with uniqueness types. This SO answer looks good: http://stackoverflow.com/questions/26309081/how-do-rusts-own...