0

While I was writing a program that works a lot with string, sometimes I got some problems with the way of turn a String to a &str.

let some_str = &string[..];

The most common problem is this.

fn main() {
    ...
    //        to forget the `[..]`   V
    let new_static_str = &some_string;
}

Meanwhile, never happened the opposite, I could do any of this to convert a &str to a String

fn main() {
    let static_str = "some text";

    let string1 = String::from(static_str);
    let string2 = static_str.to_string();
    let string3 = static_str.to_owned();
}

When I searched, I only found this way to convert a String to a &str.

Today, there is still no built-in function for this?

Nyshimori
  • 23
  • 4
  • 1
    Note that `&some_string[..]` does not give you a `'static` string. It only gives you a string slice with some non-static lifetime (`&str` not `&'static str`). – Jmb Apr 07 '23 at 13:43
  • Does it really make any difference in practice? – Nyshimori Apr 07 '23 at 13:51
  • 1
    It makes a big difference since it's not possible to get a `&'static str` from a `String` without jumping through some convoluted hoops and leaking memory, whereas it is trivial to get a non-static `&str` from a `String`. – Jmb Apr 07 '23 at 15:02

0 Answers0