stringrust

Is it necessary to use String::from() for immutable strings?


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 ?


Solution

  • Sure, there are some cases where this can be useful -- basically, any time you specifically need a String but don't have one.

    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.