Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rustc complains about seemingly valid string slice passed to a closure. #17898

Closed
simias opened this issue Oct 9, 2014 · 1 comment
Closed

Comments

@simias
Copy link

simias commented Oct 9, 2014

The following code:

pub fn main() {
    let error = | err | {
        println!("error: {}", err);
    };

    {
        let str = "foo".to_string();

        error(str.as_slice());
    }
}

Produces the following error:

test.rs:9:15: 9:18 error: `str` does not live long enough
test.rs:9         error(str.as_slice());
                        ^~~
test.rs:1:15: 11:2 note: reference must be valid for the block at 1:14...
test.rs:1 pub fn main() {
test.rs:2     let error = | err | {
test.rs:3         println!("error: {}", err);
test.rs:4     };
test.rs:5 
test.rs:6     {
          ...
test.rs:6:5: 10:6 note: ...but borrowed value is only valid for the block at 6:4
test.rs:6     {
test.rs:7         let str = "foo".to_string();
test.rs:8 
test.rs:9         error(str.as_slice());
test.rs:10     }
error: aborting due to previous error

The code builds if I annotate the closure with | err: &str|

@steveklabnik
Copy link
Member

This is intended. Closures capture references to their environment, and your str goes out of scope at the end of the block, just like the error says. This would be a dangling pointer otherwise.

lnicola pushed a commit to lnicola/rust that referenced this issue Aug 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants