Practice 12

Lifetimes

Read each program and pick an answer. Some programs do not compile, and that can be the right answer. Your choice is checked as soon as you pick it, and saved in this browser.Need a refresher? Read lesson 12.

Course

0 of 54 answered·0 correct

A Function the Compiler Cannot Check

1.

Does this compile? If it does, what does it print?

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

fn main() {
    let a = String::from("rust");
    let b = String::from("go");
    println!("{}", pick(&a, &b));
}
2.

This function only ever returns x, never y. Does it compile?

fn always_x(x: &str, y: &str) -> &str {
    x
}

fn main() {
    println!("{}", always_x("a", "b"));
}
3.

What does this print?

fn identity(x: &str) -> &str {
    x
}

fn main() {
    println!("{}", identity("hi"));
}
4.

What does this print?

fn last_word(text: &str) -> &str {
    text.split(' ').last().unwrap()
}

fn main() {
    let s = String::from("the quick brown fox");
    println!("{}", last_word(&s));
}
5.

This returns an owned String, not a reference. Does it compile?

fn combine(x: &str, y: &str) -> String {
    format!("{x}{y}")
}

fn main() {
    println!("{}", combine("rust", "lang"));
}
6.

What does this print?

fn first_n(text: &str, n: usize) -> &str {
    &text[..n]
}

fn main() {
    let s = String::from("lifetimes");
    println!("{}", first_n(&s, 4));
}
7.

What does this print?

fn shout_if_long(word: &str) -> &str {
    if word.len() > 5 {
        word
    } else {
        word
    }
}

fn main() {
    println!("{}", shout_if_long("rustacean"));
}
8.

Does this compile?

fn pick_one(a: &str, b: &str, c: &str) -> &str {
    if a.len() >= b.len() && a.len() >= c.len() {
        a
    } else if b.len() >= c.len() {
        b
    } else {
        c
    }
}

fn main() {
    println!("{}", pick_one("a", "bb", "ccc"));
}

Naming a Lifetime

9.

What does this print?

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

fn main() {
    let a = String::from("rust");
    let b = String::from("go");
    println!("{}", longest(&a, &b));
}
10.

This gives x and y two different lifetime names. Does it compile?

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

fn main() {
    let a = String::from("rust");
    let b = String::from("go");
    println!("{}", longest(&a, &b));
}
11.

Question 10 does not compile. Which first line makes it compile and still return whichever argument is longer?

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

fn main() {
    let a = String::from("rust");
    let b = String::from("go");
    println!("{}", longest(&a, &b));
}
12.

The lifetime 'a is declared but the return type does not use it. Does this compile? What does it print?

fn repeat_str<'a>(x: &'a str, times: usize) -> String {
    x.repeat(times)
}

fn main() {
    println!("{}", repeat_str("ab", 3));
}
13.

What does this print?

fn shout<'a>(text: &'a str) -> String {
    format!("{}!!!", text.to_uppercase())
}

fn main() {
    let msg = String::from("careful");
    println!("{}", shout(&msg));
}
14.

What does this print?

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

fn main() {
    let a = String::from("a");
    let b = String::from("elephant");
    println!("{}", longest(&a, &b));
}

What the Lifetime Actually Ties Together

15.

What does this print?

fn main() {
    let a = String::from("wolf");
    let result;
    {
        let b = String::from("cat");
        result = longest(&a, &b);
        println!("{result}");
    }
}
16.

This moves the println! outside the inner block. Does it compile?

fn main() {
    let a = String::from("wolf");
    let result;
    {
        let b = String::from("cat");
        result = longest(&a, &b);
    }
    println!("{result}");
}
17.

Now b is declared outside the inner block, alongside a. Does this compile? What does it print?

fn main() {
    let a = String::from("wolf");
    let b = String::from("cat");
    let result;
    {
        result = longest(&a, &b);
    }
    println!("{result}");
}
18.

What does this print?

fn main() {
    let a = String::from("hi");
    {
        let b = String::from("hello");
        let result = longest(&a, &b);
        println!("{result}");
    }
}
19.

drop(a) destroys a early. Does this compile?

fn main() {
    let a = String::from("hi");
    let b = String::from("hello");
    let result = longest(&a, &b);
    drop(a);
    println!("{result}");
}
20.

first is passed into longest a second time. What does this print?

fn main() {
    let a = String::from("sun");
    {
        let b = String::from("moonlight");
        let first = longest(&a, &b);
        let second = longest(first, &a);
        println!("{second}");
    }
}
21.

first is read after the inner block closes. Does this compile?

fn main() {
    let a = String::from("sun");
    let first;
    {
        let b = String::from("moonlight");
        first = longest(&a, &b);
    }
    println!("{first}");
}

Lifetime Elision

22.

The return type here is not a reference at all. Does this need a lifetime? What does it print?

fn word_count(s: &str) -> usize {
    s.split_whitespace().count()
}

fn main() {
    println!("{}", word_count("count these words please"));
}
23.

Two reference parameters, but the return type is bool. What does this print?

fn same_length(a: &str, b: &str) -> bool {
    a.len() == b.len()
}

fn main() {
    println!("{}", same_length("cat", "dog"));
}
24.

There is exactly one reference parameter. What does this print?

fn trim_edges(s: &str) -> &str {
    s.trim()
}

fn main() {
    println!("{}", trim_edges("  hi  "));
}
25.

Two reference parameters, and the return type is a reference too. Does this compile?

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

fn main() {
    println!("{}", shorter("a", "bb"));
}
26.

One parameter is &self. What does this print?

struct Greeting {
    text: String,
}

impl Greeting {
    fn message(&self) -> &str {
        &self.text
    }
}

fn main() {
    let g = Greeting { text: String::from("hello there") };
    println!("{}", g.message());
}
27.

describe takes &self and extra: &str, but always returns self.label. This prints two lines. Write both.

struct Counter {
    label: String,
}

impl Counter {
    fn describe(&self, extra: &str) -> &str {
        println!("note: {extra}");
        &self.label
    }
}

fn main() {
    let c = Counter { label: String::from("widgets") };
    println!("{}", c.describe("counting now"));
}
28.

Same struct, but describe now returns extra instead of self.label. Does this compile?

struct Counter {
    label: String,
}

impl Counter {
    fn describe(&self, extra: &str) -> &str {
        extra
    }
}

fn main() {
    let c = Counter { label: String::from("widgets") };
    println!("{}", c.describe("counting now"));
}
29.

What does this print?

struct Message {
    body: String,
}

impl Message {
    fn preview(&self) -> &str {
        &self.body[..3]
    }
}

fn main() {
    let m = Message { body: String::from("hello world") };
    println!("{}", m.preview());
}
30.

upper is a new String created inside shout, not a field of self. Does this compile?

struct Message {
    body: String,
}

impl Message {
    fn shout(&self) -> &str {
        let upper = self.body.to_uppercase();
        &upper
    }
}

fn main() {
    let m = Message { body: String::from("hello") };
    println!("{}", m.shout());
}
31a.

Which elision rule lets this compile with no lifetime written: fn len(s: &str) -> usize?

31b.

Which elision rule lets this compile with no lifetime written: fn echo(s: &str) -> &str?

31c.

Which elision rule lets this compile with no lifetime written: fn pick(a: &str, b: &str) -> &str?

31d.

Which elision rule lets this compile with no lifetime written: fn get(&self) -> &str?

31e.

Which elision rule lets this compile with no lifetime written: fn combine(&self, other: &str) -> &str?

Lifetimes in a Struct

32.

Does this compile?

struct Ticket {
    label: &str,
}
33.

What does this print?

struct Ticket<'a> {
    label: &'a str,
}

fn main() {
    let event = String::from("Rust Meetup");
    let ticket = Ticket { label: &event };
    println!("{}", ticket.label);
}
34.

ticket is read after event is dropped. Does this compile?

struct Ticket<'a> {
    label: &'a str,
}

fn main() {
    let ticket;
    {
        let event = String::from("Rust Meetup");
        ticket = Ticket { label: &event };
    }
    println!("{}", ticket.label);
}
35.

This prints two lines. Write both.

struct Ticket<'a> {
    label: &'a str,
}

impl<'a> Ticket<'a> {
    fn announce(&self, venue: &str) -> &str {
        println!("venue: {venue}");
        self.label
    }
}

fn main() {
    let event = String::from("Rust Meetup");
    let ticket = Ticket { label: &event };
    println!("{}", ticket.announce("Main Hall"));
}
36.

What does this print?

struct Pair<'a> {
    first: &'a str,
    second: &'a str,
}

fn main() {
    let x = String::from("alpha");
    let y = String::from("beta");
    let pair = Pair { first: &x, second: &y };
    println!("{} {}", pair.first, pair.second);
}
37.

id is an owned u32, not a reference. What does this print?

struct Note<'a> {
    title: &'a str,
    id: u32,
}

fn main() {
    let heading = String::from("Reminder");
    let note = Note { title: &heading, id: 7 };
    println!("{} {}", note.title, note.id);
}
38.

The impl block leaves out <'a>. Does this compile?

struct Ticket<'a> {
    label: &'a str,
}

impl Ticket {
    fn show(&self) -> &str {
        self.label
    }
}
39.

latest takes &mut self. What does this print?

struct Log<'a> {
    entries: &'a str,
}

impl<'a> Log<'a> {
    fn latest(&mut self) -> &str {
        self.entries
    }
}

fn main() {
    let data = String::from("start,middle,end");
    let mut log = Log { entries: &data };
    println!("{}", log.latest());
}
40.

make_ticket builds a Ticket and hands it back. What does this print?

struct Ticket<'a> {
    label: &'a str,
}

fn make_ticket<'a>(text: &'a str) -> Ticket<'a> {
    Ticket { label: text }
}

fn main() {
    let event = String::from("Rust Meetup");
    let ticket = make_ticket(&event);
    println!("{}", ticket.label);
}
41.

make_ticket now takes a second reference, venue, and neither parameter has a lifetime written on it. Does this compile?

struct Ticket<'a> {
    label: &'a str,
}

fn make_ticket(text: &str, venue: &str) -> Ticket {
    Ticket { label: text }
}

fn main() {
    let event = String::from("Rust Meetup");
    let hall = String::from("Main Hall");
    let ticket = make_ticket(&event, &hall);
    println!("{}", ticket.label);
}

The Special Lifetime 'static

42.

What does this print?

fn brand() -> &'static str {
    "made with Rust"
}

fn main() {
    println!("{}", brand());
}
43.

What does this print?

fn main() {
    let motto: &'static str = "safety first";
    println!("{motto}");
}
44.

s is a String created inside brand, not a string literal. Does this compile?

fn brand() -> &'static str {
    let s = String::from("made with Rust");
    &s
}

fn main() {
    println!("{}", brand());
}
45.

greeting is a String owned by main, not a string literal. Does this compile?

fn shout(text: &'static str) {
    println!("{}", text.to_uppercase());
}

fn main() {
    let greeting = String::from("hi there");
    shout(&greeting);
}
46.

Same shout as question 45, called with a string literal instead. What does this print?

fn shout(text: &'static str) {
    println!("{}", text.to_uppercase());
}

fn main() {
    shout("hi there");
}
47.

'static is a concrete lifetime, not a generic parameter, so the struct declares no <'a>. What does this print?

struct Brand {
    name: &'static str,
}

fn main() {
    let b = Brand { name: "Rust" };
    println!("{}", b.name);
}
48.

What does this print?

fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let a = String::from("hi");
    let b = String::from("hello");
    let result = longer(&a, &b);
    println!("{result}");
}
49.

Does this compile?

fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let a = String::from("hi");
    let result;
    {
        let b = String::from("hello");
        result = longer(&a, &b);
    }
    println!("{result}");
}
50.

What does this print?

struct Label<'a> {
    text: &'a str,
}

fn main() {
    let word = String::from("ok");
    let label = Label { text: &word };
    println!("{}", label.text);
}