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
).
4 Answers
Updated for Rust 1.0
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.
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
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
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
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.
-
54In Rust 1.10 instead of
let s_slice: &str = &s[..];
you can simply do this:let s_slice: &str = s.as_str();
– ShnatselAug 15, 2016 at 20:29 -
6Sometime, the original string doesn't live enough, like in a match {...} block. That will lead to a
's' does not live long enough error
. Nov 11, 2016 at 0:23 -
4A more general answer on how to convert between
&str
,String
,&[u8]
andVec<u8>
can be found here. Jan 9, 2021 at 17:29 -
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 the String
, 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.
fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
let mut s = String::new();
std::io::stdin().read_line(&mut s).unwrap();
let s: &'static str = string_to_static_str(s);
}
-
10
String
makes a guarantee, that as long as the object has not been dropped, the memory stays alive. Sincemem::forget
guarantees that the object will never be dropped, we are guaranteed that the reference to the containedstr
will never be invalid. Thus we can assert that it is a'static
reference– oli_obkFeb 22, 2016 at 8:58 -
2This was incredibly helpful for my Rust application, which needed to coerce a
String
into a&'static str
so that tokens created from the originalString
would be available across all threads. Without this, the Rust compiler would complain that myString
had a lifetime that ended at the end of the main function, which wasn't good enough because it didn't have the'static
guarantee.– user3704639Dec 23, 2016 at 4:30 -
1@mmstick: the better solution in that case would be to use
crossbeam
and scoped threads– oli_obkJan 9, 2017 at 8:21 -
1@ker: the application needs the string to exist across the entire lifetime of the application so I don't think that would be a better solution. There's also tokens being generated from that string which require that the original string has a static lifetime in order to be shared across threads.– user3704639Jan 16, 2017 at 19:30
-
3@mmstick: if you put your entire application into a crossbeam scope and create the string outside the scope, you get exactly that.– oli_obkJan 17, 2017 at 7:16
As of Rust version 1.26, it is possible to convert a String
to &'static str
without using unsafe
code:
fn string_to_static_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
This converts the String
instance into a boxed str
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.
-
4A use case for this that I ran into was with
clap
. I was creating an arg that specifies how many threads to use, with a default value that equals the number of logical cores on the user's machine.Arg::default_value
takes a&str
and only keeps this reference, which is usually fine because normally this value is a compile-time constant. Not true in this case though, which means I need to create a&'static str
at runtime. This is the exact solution to my problem.– cyqsimonJul 15, 2021 at 12:54
TL;DR: you can get a &'static str
from a String
which itself has a 'static
lifetime.
Although the other answers are correct and most useful, there's a (not so useful) edge case, where you can indeed convert a String
to a &'static str
:
The lifetime of a reference must always be shorter or equal to the lifetime of the referenced object. I.e. the referenced object has to live longer (or equal long) than the reference. Since 'static
means the entire lifetime of a program, a longer lifetime does not exist. But an equal lifetime will be sufficient. So if a String
has a lifetime of 'static
, you can get a &'static str
reference from it.
Creating a static
of type String
has theoretically become possible with Rust 1.31 when the const fn
feature was released. Unfortunately, the only const function returning a String
is String::new()
currently, and it's still behind a feature gate (so Rust nightly is required for now).
So the following code does the desired conversion (using nightly) ...and actually has no practical use except for completeness of showing that it is possible in this edge case.
#![feature(const_string_new)]
static MY_STRING: String = String::new();
fn do_something(_: &'static str) {
// ...
}
fn main() {
do_something(&MY_STRING);
}
'static
lifetime would imply the string never being deallocated, i.e. a memory leak. Why do you need&'static str
instead of&'a str
for some appropriate'a
?&'a str
then?as_slice
. It would be easier to help if you described what concrete problem you are trying to solve and what problems you encounter while doing so.SendStr
, a type which is either an owned string or a static string.