Skip to content

Arrays containing references eagerly default to having an unnecessarily restrictive lifetime #15196

@huonw

Description

@huonw
fn foo(x: &str) {
    let _array = ["foo", "bar", "baz", x];
}
fn main() {}
<anon>:2:40: 2:41 error: mismatched types: expected `&'static str` but found `&str` (lifetime mismatch)
<anon>:2     let _array = ["foo", "bar", "baz", x];
                                                ^
<anon>:1:17: 3:2 note: the anonymous lifetime #1 defined on the block at 1:16...
<anon>:1 fn foo(x: &str) {
<anon>:2     let _array = ["foo", "bar", "baz", x];
<anon>:3 }
note: ...does not necessarily outlive the static lifetime

This papercut comes up a bit with process spawning, where one (relatively) often writes things like ["--some-arg", "x", user_input] to build the command invocation.


One workaround is:

fn foo<'a>(x: &'a str) {
    let hack: &'a str = "foo";
    let _array = [hack, "bar", "baz", x];
}

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