How to Convert a String into a &'static Str in Rust
Created
Modified
Using slicing Syntax
To go from a String to a slice &'a str you can use slicing syntax. See the following example:
// Rust 1.0+
fn main() {
let s: String = "abc".to_owned();
// take a full slice of the string
let slice: &str = &s[..];
println!("{}", slice);
}
abc
Using & Operator
You can use the fact that String implements Deref<Target=str> and perform an explicit reborrowing:
fn main() {
let s: String = "abc".to_owned();
// *s : str (via Deref<Target=str>)
// &*s: &str
let slice: &str = &*s;
println!("{}", slice);
}
abc
Using unsafe Code
As of Rust version 1.26, it is possible to convert a String to &'static str without using unsafe code:
// Rust 1.26+
fn string_to_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
let s: String = "abc".to_owned();
let slice: &str = string_to_str(s);
println!("{}", slice);
}
abc