Generic Lifetimes

Additional Resources

Exercises

Helping the borrow checker

// Make the code compile by completing the function signature.

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

fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is '{}'", result);
}
Solution
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  if x.len() > y.len() {
      x
  } else {
      y
  }
}

fn main() {
  let string1 = String::from("abcd");
  let string2 = "xyz";

  let result = longest(string1.as_str(), string2);
  println!("The longest string is '{}'", result);
}

Complying with the borrow checker

// Make the code compile. You can only shift one statement.
// You can not shift variable declarations.

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

fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    }
    println!("The longest string is '{}'", result);
}
Solution
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  if x.len() > y.len() {
      x
  } else {
      y
  }
}

fn main() {
  let string1 = String::from("long string is long");
  let result;
  {
      let string2 = String::from("xyz");
      result = longest(string1.as_str(), string2.as_str());
      println!("The longest string is '{}'", result);
  }
}

Struct lifetimes

// Something is missing from our struct definition. Can you fix it?

struct Book {
    author: &str,
    title: &str,
}

fn main() {
    let name = String::from("Jill Smith");
    let title = String::from("Fish Flying");
    let book = Book {
        author: &name,
        title: &title,
    };

    println!("{} by {}", book.title, book.author);
}
Solution
struct Book<'a> {
  author: &'a str,
  title: &'a str,
}

fn main() {
  let name = String::from("Jill Smith");
  let title = String::from("Fish Flying");
  let book = Book {
      author: &name,
      title: &title,
  };

  println!("{} by {}", book.title, book.author);
}