What's the preferred way to create a String from a literal?

后端 未结 1 982
小鲜肉
小鲜肉 2021-01-22 23:08

Is there a performance or stylistic reason to prefer one of the following forms for creating a String from a literal in Rust?

\"hello world\".to_string()
format!         


        
相关标签:
1条回答
  • 2021-01-23 00:05

    The idiomatic way in the Rust compiler internals and thus Rust in general is to use to_string. It is done this way in the compiler and backed by Alex Crichton in three pull requests (1, 2, 3) that tried to change this.

    The argument is that to_string most clearly defines what you want. Performance-wise both to_string and format! are slower than String::from. But once we get impl specialization there's a good chance that they will perform exactly the same.


    That said, clippy lints against "abc".to_string() and suggests "abc".to_owned().

    0 讨论(0)
提交回复
热议问题