snippetrustCritical
How to convert a String into a &'static str
Viewed 0 times
howstrconvertstaticstringinto
Problem
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).Solution
Updated for Rust 1.0
You cannot obtain
To go from a
Alternatively, you can use the fact that
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
Note that this pattern is not unique for
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 stringAlternatively, you can use the fact that
String implements Deref and perform an explicit reborrowing:let s_slice: &str = &*s; // s : String
// *s : str (via Deref)
// &*s: &strThere 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 &strNote 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.Code Snippets
let s: String = "abcdefg".to_owned();
let s_slice: &str = &s[..]; // take a full slice of the stringlet s_slice: &str = &*s; // s : String
// *s : str (via Deref<Target=str>)
// &*s: &strlet 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 &strContext
Stack Overflow Q#23975391, score: 259
Revisions (0)
No revisions yet.