将字符串转换为 &str 的惯用方法是什么? [英] What is the idiomatic way to convert a String to &str?

查看:30
本文介绍了将字符串转换为 &str 的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了多种将 String 转换为 &str 的方法.今天哪一个是正确/惯用的?

I've found a number of ways to convert String to &str. Which one is correct/idiomatic today?

let string = "hello".to_string();

let string_slice1 = &string[..];
let string_slice2: &str = &string;
let string_slice3 = &*string;

如何在变量声明中不指定类型的情况下使第二种方法起作用?类似于 &string as &str (但它不起作用).我看到 &string 具有 &String 类型,但是当它隐式转换为 &str 时,它将执行隐式转换.我如何使这种转换显式?

How would I make the second method work without specifying type in variable declaration? Something like &string as &str (but it doesn't work). I see that &string has &String type but when it is implicitly cast to &str, it will perform implicit conversion. How do I make that conversion explicit?

推荐答案

String 实现了两件重要的事情:

There are two important things here that String implements:

  • Index:这使得 string[..] 成为 str 类型,尽管你需要引用它(通过调用方法,允许自动引用发生,或显式为 &string[..]).这解释了 string_slice1.

  • Index<RangeFull, Output = str>: this makes string[..] be of type str, though you need to take a reference to it (either by calling a method, allowing autoref to happen, or explicitly as &string[..]). This explains the string_slice1.

Deref<Target = str>:这使得 *string 成为 str 类型,对非大小类型的考虑相同就像在索引中一样.这就是 string_slice3 起作用的原因以及 string_slice2 起作用的一些隐藏行为的原因.

Deref<Target = str>: this makes *string be of type str, with the same considerations on unsized types as in indexing. This is why string_slice3 works and in a bit of hidden behaviour why string_slice2 works.

与 C++ 不同,& 不是纯引用运算符:它还允许先解除引用.因此,&string 通常是 &String 类型,但如果有必要,它也可以是 &str 类型.例如,如果您将其传递给采用 &str 的方法,它就会起作用,或者如果您尝试将其绑定到 &str<类型的变量/代码>.这就是为什么 : &str 在这种情况下是必要的.

Unlike in C++, & is not a pure reference operator: it also allows dereferencing to take place first. &string will therefore normally be of type &String, but it is possible for it to be of type &str if necessary also. If, for example, you were to pass it to a method that took a &str, it would work, or if you try to bind it to a variable of type &str. This is why the : &str is necessary for this case.

普遍的共识是在可行的情况下应该避免类型归属,所以第二种形式是不可取的.在第一个和第三个之间,对于哪个更可取还没有达成共识.

General consensus is that type ascription is to be avoided where feasible, so the second form is not desirable. Between the first and third, there is no consensus as to which is more desirable yet.

还有 String::as_str,有些人更喜欢:

There's also String::as_str, which some prefer:

let string_slice4 = string.as_str();

这篇关于将字符串转换为 &amp;str 的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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