Skip to content

Functions with signature fn (&str) -> &str can return string literals (&'static str) #16083

@japaric

Description

@japaric

Explanation in the comments:

// The first two functions *require* the `'static` lifetime specifier
fn foo() -> &'static str {
    "foo"
}

fn bar(_: int) -> &'static str {
    "bar"
}

// In this function the `'static` specifier is *not* required, see next function
fn baz(_: &str) -> &'static str {
    "baz"
}

// Is the actual signature `fn bar<'a>(_: &'a str) -> &'a str` because of lifetime elision?
// Or does this function have the same signature as `baz`?
// In the former case, since the return type is `&'static str`, does that mean that `a` === `static` ?
fn quux(_: &str) -> &str {
    "quux"
}

fn main() {
    let string = "String".to_string();
    let slice = string.as_slice();

    // `slice` doesn't have `&'static str` type, but it's accepted by `quux`
    // that means that `baz` and `quux` have the same signature
    println!("{}", quux(slice));
    println!("{}", baz(slice));
}

TL;DR quux can be ambiguous to the reader because of lifetime elision rules. I think we should forbid functions with signature fn (&str) -> &str that actually return &'static str. Instead of quux, programmers should use baz.

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