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
).
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
- Destructure a vector into variables and give away
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
- How do I initialize an opaque C struct when using
- What's the most idiomatic way to test two Opti
Updated for Rust 1.0
You cannot obtain
&'static str
from aString
becauseString
s do not live for the entire life of your program, and that's what&'static
lifetime means. You can only get a slice parameterized byString
own lifetime from it.To go from a
String
to a slice&'a str
you can use slicing syntax:Alternatively, you can use the fact that
String
implementsDeref<Target=str>
and perform an explicit reborrowing: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:Note that this pattern is not unique for
String
/&str
- you can use it with every pair of types which are connected throughDeref
, for example, withCString
/CStr
andOsString
/OsStr
fromstd::ffi
module orPathBuf
/Path
fromstd::path
module.As of Rust version 1.26, it is possible to convert a
String
to&'static str
without usingunsafe
code:This converts the
String
instance into a boxedstr
and immediately leaks it. This frees all excess capacity the string may currently occupy.Note that there are almost always solutions that are preferable over leaking objects, e.g. using the
crossbeam
crate if you want to share state between threads.You can do it, but it involves leaking the memory of the
String
. This is not something you should do lightly. By leaking the memory of theString
, we guarantee that the memory will never be freed (thus the leak). Therefore, any references to the inner object can be interpreted as having the'static
lifetime.