Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

Question about Rust Static Lifetime and scope

I recently in study Rust,But stop in lifetime.anyone can help me? I'm trying to Make a string literal with static lifetime,but When it goes out of scope, the reference can no longer be used.

fn main(){
 {
  let s: &'static str = "hello world";
 }
  println("s={}",s);
}

I got an error: s not found in this scope I'm trying to use static keyword

fn main(){
 {
  static s: &'static str = "hello world";
 }
  println("s={}",s);
}

still the same. It any diffent between static keyword,static lifetime and scope? Thanks!

question from:https://stackoverflow.com/questions/65622779/question-about-rust-static-lifetime-and-scope

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...