191

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).

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Christoph
  • 26,519
  • 28
  • 95
  • 133
  • That doesn't seem possible nor desirable. `'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`? –  May 31 '14 at 23:39
  • 3
    How would it look to convert it into `&'a str ` then? – Christoph May 31 '14 at 23:42
  • Via `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. –  May 31 '14 at 23:46
  • Also note [`SendStr`](http://doc.rust-lang.org/std/str/type.SendStr.html), a type which is either an owned string or a static string. – Chris Morgan Jun 01 '14 at 13:36

4 Answers4

250

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.

Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296
101

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().

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
oli_obk
  • 28,729
  • 6
  • 82
  • 98
  • 1
    `String` makes 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. – George Hilliard Feb 22 '16 at 03:06
  • 12
    `String` makes a guarantee, that as long as the object has not been dropped, the memory stays alive. Since `mem::forget` guarantees that the object will never be dropped, we are guaranteed that the reference to the contained `str` will never be invalid. Thus we can assert that it is a `'static` reference – oli_obk Feb 22 '16 at 08:58
  • 3
    This was incredibly helpful for my Rust application, which needed to coerce a `String` into a `&'static str` so that tokens created from the original `String` would be available across all threads. Without this, the Rust compiler would complain that my `String` 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. –  Dec 23 '16 at 04:30
  • 1
    @mmstick: the better solution in that case would be to use `crossbeam` and scoped threads – oli_obk Jan 09 '17 at 08: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. –  Jan 16 '17 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_obk Jan 17 '17 at 07:16
  • 1
    This answer is great! It both told me how to deviously create a static string slice and convinced me not to do it! I chose to refactor my app to not use static string slices in so many places. – Paul Chernoch Sep 16 '19 at 15:42
  • does the rust program frees the memory of the leaked &'static str at the end of runtime ? or do we get here a os memory leak that would be freed at computer shut down ? – alexzander Jul 07 '22 at 14:38
44

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 5
    A 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. – cyqsimon Jul 15 '21 at 12:54
6

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);
}
Zargony
  • 9,615
  • 3
  • 44
  • 44