Ad
  • Custom User Avatar

    A 'static reference lasts for the entire duration of the program, even longer than main, which makes sense because we've literally typed it into the source code, so the string will always be the same.

    The reason it's necessary is less intuitive, but important for understanding the rust lifetime system as a whole. When we return a reference, we're promising that something will actually be there, but when our function ends everything will be dropped! This is why solutions that return a String work, Strings are just fancy pointers, so we've allocated a place for our String and it will be dropped whenever the caller drops it.

    With that in mind, how come a 'static reference actually works, what can it even be referencing? Well, it's a little bit tricky and actually references a string embedded in the program itself!
    Godbolt is really helpful here, you can literally see "hello world" here: https://godbolt.org/z/xGhWW6Mbq

    In the string version, though, it's nowhere to be found: https://godbolt.org/z/14vevMYco

    In a nutshell, we use 'static because it tells the compiler that the string lasts for the entire duration of the program, which is possible because it's embedded in the program, and is preferable because it lets us avoid a heavy String for such a simple task.

  • Custom User Avatar