如何直接创建一个String? [英] How to create a String directly?

查看:47
本文介绍了如何直接创建一个String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我需要一个字符串时,有什么方法可以避免调用 .to_string() 吗?例如:

Is there any way to avoid calling .to_string() when I need a string? For example:

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

而不是

func1("fdsfdsfd".to_string())

我可以这样做吗:

func1(s"fdsfdsfd")

推荐答案

TL;DR:

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

As of Rust 1.9, str::to_string, str::to_owned, String::from, str::into all have the same performance characteristics. Use whichever you prefer.

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

The most obvious and idiomatic way to convert a string slice (&str) to an owned string (String) is to use ToString::to_string. This works for any type that implements Display. This includes string slices, but also integers, IP addresses, paths, errors, and so on.

在 Rust 1.9 之前,to_stringstr 实现利用了 格式化基础设施.虽然它有效,但它是矫枉过正,而不是最高效的路径.

Before Rust 1.9, the str implementation of to_string leveraged the formatting infrastructure. While it worked, it was overkill and not the most performant path.

更轻松的解决方案是使用 ToOwned::to_owned,它是为具有借用"和拥有"对的类型实现的.它以一种高效的方式实现.

A lighter solution was to use ToOwned::to_owned, which is implemented for types that have a "borrowed" and an "owned" pair. It is implemented in an efficient manner.

另一个轻量级的解决方案是使用 Into::into 它利用了 From::from.这也是有效实施.

Another lightweight solution is to use Into::into which leverages From::from. This is also implemented efficiently.

对于您的特定情况,最好的做法是接受 &str,如 3340 个回答.然后你需要做零分配,这是最好的结果.

For your specific case, the best thing to do is to accept a &str, as thirtythreeforty answered. Then you need to do zero allocations, which is the best outcome.

一般来说,如果我需要分配一个字符串,我可能会使用 into —— 它只有 4 个字母长 ^_^.在回答有关 Stack Overflow 的问题时,我将使用 to_owned,因为它更清楚发生了什么.

In general, I will probably use into if I need to make an allocated string — it's only 4 letters long ^_^. When answering questions on Stack Overflow, I'll use to_owned as it's much more obvious what is happening.

这篇关于如何直接创建一个String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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