如何直接创建String?

时间:2015-07-10 02:08:40

标签: rust

当我需要字符串时,有没有办法避免调用.to_string()?例如:

fn func1(aaa: String) -> ....

而不是

func1("fdsfdsfd".to_string())
我可以这样做:

func1(s"fdsfdsfd")

3 个答案:

答案 0 :(得分:12)

不,str::to_string()方法是从String(字符串文字)创建&'static str的规范方法。我甚至喜欢它,因为你不喜欢它:它有点冗长。因为它涉及堆分配,所以在调用它们之前应该三思而后行。另请注意,自Rust gained impl specialization起,str::to_string不会慢于str::to_owned或其同类。

但是,您真正想要的是func1,可以轻松传递任何字符串,无论是&str还是String。由于String Deref &strfunc1,您可以&str接受fn func1(s: &str) { println!("{}", s); } fn main() { let allocated_string: String = "owned string".to_string(); func1("static string"); func1(&allocated_string); } ,从而完全避免字符串分配。请参阅此示例(playground):

ParsePush push = new ParsePush();
Dictionary<string, object> pushData = new Dictionary<string, object>()
{
    {"alert", message},
    {"sound", ""},
    {"badge", 0},
    {"uri", "http://blog.parse.com"},
    {"category", category}
};
push.Data = pushData;
push.Query = query;
push.SendAsync().Wait();

答案 1 :(得分:11)

TL; DR:

Rust 1.9起,str::to_stringstr::to_ownedString::fromstr::into都具有相同的性能特征。使用您喜欢的任何一种。

将字符串切片(&str)转换为拥有的字符串(String)的最明显和惯用的方法是使用ToString::to_string。这适用于任何实现Display的类型。这包括字符串切片,还包括整数,IP地址,路径,错误等。

在Rust 1.9之前,str to_string的实施利用了formatting infrastructure。虽然它有效,但它是过度杀伤而不是最高效的路径。

较轻的解决方案是使用ToOwned::to_owned,它是针对具有“借用”和“拥有”对的类型实现的。它是implemented in an efficient manner

另一个轻量级解决方案是使用Into::into来利用From::from。这也是implemented efficiently

对于特定的案例,最好的办法是接受&strthirtythreeforty answered。然后你需要做零分配,这是最好的结果。

一般情况下,如果我需要创建一个已分配的字符串,我可能会使用into - 它只有4个字母长^ _ ^。在回答关于Stack Overflow的问题时,我会使用to_owned,因为它更明显地发生了什么。

答案 2 :(得分:0)

  

我现在强烈建议使用to_owned()字符串文字而不是to_string()into()

     

String&str之间有什么区别?一个令人不满意的答案是“一个是字符串而另一个不是字符串”,因为显然两者都是字符串。拿一些字符串并使用to_string()将其转换为字符串似乎错过了我们为什么要这样做的原因,更重要的是错过了向我们的读者记录这一点的机会。

     

String和&amp; str之间的区别在于一个是拥有的而一个不是拥有的。使用to_owned()可以完全捕获我们代码中特定位置需要转换的原因。

struct Wrapper {
    s: String
}

// I have a string and I need a string. Why am I doing this again?
Wrapper { s: "s".to_string() }

// I have a borrowed string but I need it to be owned.
Wrapper { s: "s".to_owned() }
  

如果您在心理上将to_string视为to_String

,则不会

https://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441/6?u=rofrol