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 badges1 Answer
Reset to default 3Sure, 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 ownedString
. (Caveat: You could useCow<str, 'static>
which allows you to use both&'static str
andString
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
版权声明:本文标题:rust - Is it necessary to use String::from() for immutable strings? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744271872a2598221.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论