0

Can I create a binding with the type Option<&str>? Tiny non-working example:

fn main() {
    let a: Option<&str> = {
        Some(&{"a".to_string() + "b"}) // Let's say the string is not static
    };
}

This does not work, I need to add lifetime (or use a Option<String> without &). So how can I declare lifetime here? I know I can return a Option<String> and everything will be fine, but that's not what I want — I'm trying to understand some Rust mechanics. I can declare lifetime in a function, but don't know how to do this in a simple let binding.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rap-2-h
  • 30,204
  • 37
  • 167
  • 263

3 Answers3

2

Absolutely:

fn main() {
    let s = "a".to_string() + "b";
    let a: Option<&str> = Some(&s);
}

The problem is not in creating a Option<&str>, it's that you are trying to take a reference to something that has gone out of scope. This is (a part of) the error message for the original code:

error: borrowed value does not live long enough
  |>         Some(&{"a".to_string() + "b"})
  |>               ^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough

See Return local String as a slice (&str) for further information.

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
1

You need to extend lifetime of the string beyond a's initializer expression by binding it to another name:

fn main() {
    let x: String = "a".to_string() + "b";
    let a: Option<&str> = {
        Some(&x)
    };
}
yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
1

You are trying to keep a reference to a value that does not live long enough, like the error says:

3 |>         Some(&{"a".to_string() + "b"}) // Let's say the string is not static
  |>               ^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough

You can have a bind of type Option<&str>, but the reference must live longer than the bind. In your example, you create a bind to the result string, an than take a reference to it:

fn main() {
    let x: String = "a".to_string() + "b";
    let a: Option<&str> = Some(&x);
}
malbarbo
  • 10,717
  • 1
  • 42
  • 57