Scope is not the same thing as lifetime. In most cases, they are similar:
fn main() {
{ // scope starts here with '{'
let foo = Foo::new(); // create a new variable inside scope
} // scope ends here. Every owned value inside scope is deallocated.
// foo is inaccessible here
}
Even if the lifetime of your variable is greater than the enclosing scope, that does not mean you will be able to access it outside of the scope. Rather, the lifetime just tells you for how long a certain variable is valid.
One way to think about this is that all variables are owned. Even references. You can imagine that a variable holding a certain reference is owning the reference (not the actual value itself). When the variable holding the reference goes out of scope, the "owned" reference gets dropped as well but not the actual value.
In your example, s
is owning a reference to a str
. When s
goes out of scope, the reference is dropped but not the actual str
itself that it's pointing to (which is 'static
so it's not dropped until the program terminates).
Since the reference is dropped, you are no longer able to access it.
As in your example, just put the declaration of s
in the same or larger scope than where you would use it. Since the str
is 'static
and is constant, you can just make a global variable:
static s: &str = "Hello World!"; // note that 'static is implicit
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…