Skip to content

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

Closed
@simias

Description

@simias

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|

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions