1

This snippet doesn't compile because the struct A instance outlives the reference s2 it holds in its field s. No problem.

struct A<'a> {
    s: &'a usize,
}

let s1 = 100;

let mut a = A { s: &s1 };

{
    let s2 = 1000;

    a.s = &s2;
}

In the same situation for string literals, it compiles. Why?

struct A<'a> {
    s: &'a str,
}

let s1 = "abc";

let mut a = A { s: &s1 };

{
    let s2 = "abcd";

    a.s = &s2;
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
周汉成
  • 1,217
  • 2
  • 13
  • 24

1 Answers1

5

Per The Rust Programming Language, all string literals have the special 'static lifetime.

So in your example you have an A<'static> and you're changing which &'static str it holds.

turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
  • Actually, as I linked in a comment, all literals have the `'static` lifetime. – Boiethios Sep 27 '18 at 07:49
  • @Boiethios that's not fully true... in fact OPs post *shows* it isn't true as they are using the literal `100` / `1000`. It's only when you immediately take a reference to a literal can the compiler promote it to a `static` variable. – Shepmaster Sep 27 '18 at 13:57
  • @Shepmaster Well, it depends what you call a literal. I'm not sure that 100/1000 is a literal. – Boiethios Sep 27 '18 at 14:05
  • 1
    @Boiethios `100` / `1000` is 100% a literal. A literal that is stored in a variable. If you take a reference to the literal, [it works](https://play.rust-lang.org/?gist=95c25c21aac510462c3063767a5428cb&version=stable&mode=debug&edition=2015). In OP's case they are taking a reference to the variable and it doesn't. – Shepmaster Sep 27 '18 at 14:07