I just started learning rust. But I have to ask to satisfy my curiosity. Here it goes.
I know that push_str will throw error in both cases since I haven't used mut keyword anywhere.
fn main() {
let my_string1 = "Hello, world! 1";
let my_string2 = String::from("Hello, world! 2");
my_string1.push_str("My new String 1");
my_string2.push_str("My new String 2");
}
But I am seeing in every tutorial people using String::from but they don't make it mutable. Is there any reason to use String::from if your string is not going to mutate ever ? Can't we directly define it like my_string1 above with type &str ?
So basically I meant to ask that String::from make sense only with mut keyword ?
Sure, there are some cases where this can be useful -- basically, any time you specifically need a String
but don't have one.
HashMap<String, _>
because some of the keys will be dynamic. In that case even the non-dynamic strings need to be converted to an owned String
. (Caveat: You could use Cow<str, 'static>
which allows you to use both &'static str
and String
in the same container at the cost of requiring a branch to access the contents.)String
.mut
.I'm sure some tutorial examples don't strictly need a String
and could get by with a &str
. We'd need to see specific examples to evaluate whether that's the case, but we cannot categorically say that converting a &'static str
to a String
is never useful.