RustCurious.com
Rust explained carefully.

Lesson 12

Lifetimes

The most unfamiliar concept for newcomers to Rust: Lifetimes specify the constraints on references. With named lifetimes we have greater flexibility when returning references from functions and methods.

Coding Practice

Exercise 1: Max Mut

Open in playground

// https://rustcurious.com/12

// Exercise: Max Mut
//
// Fix the compile error so the unit test passes.

pub fn max_mut(x: &mut i32, y: &mut i32) -> &mut i32 {
    if *x > *y { x } else { y }
}

// -------------------------------------------------------
// No need to change anything below this line.

#[test]
fn test() {
    let mut a = 20;
    let mut b = 10;

    *max_mut(&mut a, &mut b) += 1;
    assert_eq!(a, 21);

    *max_mut(&mut b, &mut a) += 2;
    assert_eq!(a, 23);
}

 

Exercise 2: Action

Open in playground

// https://rustcurious.com/12

// Exercise: Action
//
// Fix the compile error so the program runs.

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum Action {
    Like,
    Subscribe,
}

impl Action {
    pub fn verb(&self) -> &str {
        match self {
            Action::Like => "Like",
            Action::Subscribe => "Subscribe",
        }
    }
}

// -------------------------------------------------------
// No need to change anything below this line.

fn random_action() -> Action {
    if rand::random() {
        Action::Like
    } else {
        Action::Subscribe
    }
}

fn main() {
    // Don't change this:
    let verb = random_action().verb();
    println!("{}!", verb);
}

 

Exercise 3: Action Language

Open in playground

// https://rustcurious.com/12

// Exercise: Action Language
//
// Fix the compile error so the unit test passes.

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum Action {
    Like,
    Subscribe,
}

impl Action {
    pub fn sentence(&self, lang: &Lang) -> &str {
        &lang[self]
    }
}

// -------------------------------------------------------
// No need to change anything below this line.

use std::collections::HashMap;

pub type Lang = HashMap<Action, String>;

#[test]
fn test() {
    let spanish: Lang = [
        (Action::Like, "Dale a me gusta".into()),
        (Action::Subscribe, "¡Suscríbete a RustCurious!".into()),
    ].into();

    assert_eq!(
        Action::Like.sentence(&spanish),
        "Dale a me gusta",
    );
    assert_eq!(
        Action::Subscribe.sentence(&spanish),
        "¡Suscríbete a RustCurious!",
    );
}