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 Strings 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.
-
68In Rust 1.10 instead of
let s_slice: &str = &s[..];you can simply do this:let s_slice: &str = s.as_str();– ShnatselCommented Aug 15, 2016 at 20:29 -
7Sometime, the original string doesn't live enough, like in a match {...} block. That will lead to a
's' does not live long enough error. Commented Nov 11, 2016 at 0:23 -
8A more general answer on how to convert between
&str,String,&[u8]andVec<u8>can be found here. Commented 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);
}
Since Rust 1.72, we got the String::leak() function:
fn string_to_static_str(s: String) -> &'static str {
s.leak()
}
Note this does not drop excess capacity. If you want to do that, use into_boxed_str().
-
1
Stringmakes no guarantee in its API (as far as I'm aware; correct me if I'm wrong) that the memory it points to will be on the heap. In practice, this is probably fine, but you can't prove that you won't use-after-free memory that may have been on the stack, for example. Commented Feb 22, 2016 at 3:06 -
12
Stringmakes a guarantee, that as long as the object has not been dropped, the memory stays alive. Sincemem::forgetguarantees that the object will never be dropped, we are guaranteed that the reference to the containedstrwill never be invalid. Thus we can assert that it is a'staticreference– oli_obkCommented Feb 22, 2016 at 8:58 -
3This was incredibly helpful for my Rust application, which needed to coerce a
Stringinto a&'static strso that tokens created from the originalStringwould be available across all threads. Without this, the Rust compiler would complain that myStringhad a lifetime that ended at the end of the main function, which wasn't good enough because it didn't have the'staticguarantee.– user3704639Commented Dec 23, 2016 at 4:30 -
1@mmstick: the better solution in that case would be to use
crossbeamand scoped threads– oli_obkCommented Jan 9, 2017 at 8:21 -
3@mmstick: if you put your entire application into a crossbeam scope and create the string outside the scope, you get exactly that.– oli_obkCommented Jan 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.
-
5A 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_valuetakes a&strand 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 strat runtime. This is the exact solution to my problem.– cyqsimonCommented Jul 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);
}
'staticlifetime would imply the string never being deallocated, i.e. a memory leak. Why do you need&'static strinstead of&'a strfor some appropriate'a?&'a strthen?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.