rust - String::from ("") & "".to_string() 在 Rust 中有何不同?

标签 rust

String::from("") & "".to_string() 在 Rust 中有何不同?

两种情况下的栈和堆分配有什么不同吗?

最佳答案

How does String::from("") & "".to_string() differ in Rust?

它们是不同协议(protocol)(特征)的一部分:std::convert::Fromalloc::string::ToString [0].

但是,当涉及到 &str/String 时,它们会做同样的事情(就像 "".to_owned() 一样)。

Is there any difference in stack and heap allocation in both cases?

正如 joelb 的链接所表明的,在 Rust 1.9 之前,"".to_string() 在遍历整个字符串格式化机制时明显比替代方案慢。现在已经不是这样了。


[0] `ToString` 如果结构实现了`Display`,也会自动实现[1]

[1] 功能上 s.to_string() 等价于 format!("{}", s),一般建议直接实现 ToString,除非绕过格式化机制可以提供显着的性能改进(这就是 str/String 这样做的原因)

关于rust - String::from ("") & "".to_string() 在 Rust 中有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475158/

相关文章:

rust - 为什么我可以用引用的引用来调用接受引用的函数?

json - 错误 : type `&[str]` does not implement any method in scope named `encode`

regex - 如何遍历字符串并替换某些短语?

rust - 如何为 Iterator::filter_map 指定类型信息?

rust - 当第二个参数用'a注释时,第一个参数的隐式生存期是多少?

regex - 花式正则表达式未在输入中返回所有匹配项

rust - 如何启用 Rust "crate feature"?

rust - 如何访问 Actix-web 中 Future 中的 HttpRequest 数据?

rust - 如何在 Rust 中内联 ASM 字节语句?

rust - 如何导出同名的函数和宏?