8000 Improved lifetimes explanation with a more complete code-snippet · Issue #4400 · rust-lang/book · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Improved lifetimes explanation with a more complete code-snippet #4400
Closed
@iampi31415

Description

@iampi31415

Generic lifetimes in functions says:

(...) [the] return type needs a generic lifetime parameter on it because Rust can’t tell whether the reference being returned refers to x or y.

The code snippet is:

fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() { x } else { y }
}

This example would be enhanced with context afterwards:

fn main() {
    let result: &str;
    let x = "hi";
    {
        let y = String::from("world");// freed at end of block
        result = longest(x, y.as_str());
    }
    // now result is a dangling pointer
    println!("{result}");
}

fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() { x } else { y }
}

This would provide an easier understanding of why the lifetime matters. To an extent you have provided this example at the beginning (without a function) but the context seems to matter a lot here as well.

Interestingly, the example passes using static strings, since those live "forever". Which was 🍭 so confusing to me as well 🍭

cc @StefanSalewski, @carols10cents. In case you have an opinion.

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

      2A04
      0