从文字创建字符串的首选方法是什么? [英] What's the preferred way to create a String from a literal?

查看:42
本文介绍了从文字创建字符串的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了从 Rust 中的文字创建字符串,是否有更喜欢以下形式之一的性能或风格原因?

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!("hello world")
String::from("hello world")

推荐答案

Rust 编译器内部的惯用方式,因此 Rust 通常使用 to_string.它是在编译器中以这种方式完成的,并由 Alex Crichton 在三个拉取请求中提供支持 (123) 试图改变这一点.

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.

论点是 to_string 最清楚地定义了你想要什么.to_stringformat! 在性能方面都比 String::from 慢.但是一旦我们获得了 impl 专业化,它们很有可能会执行完全相同的操作.

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.

也就是说,clippy lints 对 "abc".to_string() 并建议 "abc".to_owned().

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

这篇关于从文字创建字符串的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆