如何将字符串转换为 &'static str [英] How to convert a String into a &'static str
问题描述
如何将 String
转换为 &str
?更具体地说,我想将其转换为具有 static
生命周期 (&'static str
) 的 str
.
How do I convert a String
into a &str
? More specifically, I would like to convert it into a str
with the static
lifetime (&'static str
).
推荐答案
针对 Rust 1.0 更新
您无法从 String
中获取 &'static str
因为 String
可能不会在您的程序的整个生命周期中存活,并且这就是 &'static
生命周期的含义.您只能从中获取由 String
自己的生命周期参数化的切片.
You cannot obtain &'static str
from a String
because String
s may not live for the entire life of your program, and that's what &'static
lifetime means. You can only get a slice parameterized by String
own lifetime from it.
要从 String
到切片 &'a str
,您可以使用切片语法:
To go from a String
to a slice &'a str
you can use slicing syntax:
let s: String = "abcdefg".to_owned();
let s_slice: &str = &s[..]; // take a full slice of the string
或者,您可以使用 String
实现 Deref
并执行显式再借用的事实:
Alternatively, you can use the fact that String
implements Deref<Target=str>
and perform an explicit reborrowing:
let s_slice: &str = &*s; // s : String
// *s : str (via Deref<Target=str>)
// &*s: &str
还有另一种方法可以实现更简洁的语法,但只有在编译器能够确定所需的目标类型(例如在函数参数或显式类型化的变量绑定中)时才能使用它.它被称为 deref coercion,它允许只使用 &
运算符,编译器将根据上下文:
There is even another way which allows for even more concise syntax but it can only be used if the compiler is able to determine the desired target type (e.g. in function arguments or explicitly typed variable bindings). It is called deref coercion and it allows using just &
operator, and the compiler will automatically insert an appropriate amount of *
s based on the context:
let s_slice: &str = &s; // okay
fn take_name(name: &str) { ... }
take_name(&s); // okay as well
let not_correct = &s; // this will give &String, not &str,
// because the compiler does not know
// that you want a &str
请注意,此模式对于 String
/&str
不是唯一的 - 您可以将它用于通过 Deref连接的每一对类型code>,例如,使用
CString
/CStr
和 OsString
/OsStr
来自 std::ffi
模块或 PathBuf
/来自
.std::path
模块的路径
Note that this pattern is not unique for String
/&str
- you can use it with every pair of types which are connected through Deref
, for example, with CString
/CStr
and OsString
/OsStr
from std::ffi
module or PathBuf
/Path
from std::path
module.
这篇关于如何将字符串转换为 &'static str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!