admin管理员组

文章数量:1401836

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 ?

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 ?

Share Improve this question edited Mar 23 at 19:27 cdhowie 170k25 gold badges299 silver badges319 bronze badges asked Mar 23 at 19:18 Niranjan WaghNiranjan Wagh 276 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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

  • Maybe you have a 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.)
  • Maybe you are passing the string to some other API that requires a String.
  • Maybe you will rebind the string later as 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.

本文标签: rustIs it necessary to use Stringfrom() for immutable stringsStack Overflow