Skip to content

Listing 1.13 Lifetimes #14

Description

@Azaravicius

In example shown in Listing 1.13 we don't need lifetime for y

It should be

fn longest_common_prefix<'a>(x: &'a str, y: &str) -> &'a str`

This is because function does not return reference to y. Code works for current example, but it will not work if we replace main() with this:

fn main() {
    let string1 = String::from("abc");;
    let result;
    {
        let string2 = String::from("abdef");
        result = longest_common_prefix(&string1, &string2);
    }
    println!("The longest common prefix is: {}", result);
}

because string2 don't live as long as result. In current example it only works because both strings are static.
Current example makes lifetimes confusing and example meaningless for lifetimes.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions