Learn/Rust/10. Structuring data
Lesson 10 of 15
Sign in

Rust, lesson 10

Structuring data

Rust models data with two building blocks: a struct groups several values that belong together ("a player has a name AND health AND a level"), and an enum says a value is one of several variants ("a shape is a circle OR a rectangle"). Add methods to either with an impl block, and you have everything a class gives you in other languages.

Structs

Every field must be given a value when you create the struct. To change a field, the whole binding must be mut; Rust has no per-field mutability.

When a variable has the same name as a field, you can use the shorthand Player { name, health, level: 1 }.

Methods with impl

Methods live in an impl block. Their first parameter says how they use the value:

  • &self reads it,
  • &mut self changes it,

2 exercises to try what you just read.

Exercise 1

Rectangles

Press Ctrl Enter or Check to test your code.

Exercise 2

Robot moves

Press Ctrl Enter or Check to test your code.

  • self takes ownership (consumes it).
  • Functions in the block without self are associated functions, called with ::. The conventional constructor is new.

    Inside an impl, Self is a shorthand for the type's own name.

    Deriving traits

    A trait is a set of behaviour a type can have. Some common ones can be generated for you with #[derive(...)] above the type:

    Debug enables {:?} printing, Clone adds .clone(), PartialEq adds ==. To control how a type prints with plain {}, implement std::fmt::Display yourself, as you saw in lesson 9.

    Enums with data

    Each enum variant can carry its own data, in tuple or struct form:

    match unpacks the data while choosing the branch, and the compiler checks you handled every variant. Add a new variant later and every match that forgot it becomes a compile error, which is exactly where you need to update code. Option and Result are simply enums defined this way in the standard library.

    Tuple structs

    A struct can have unnamed fields, accessed with .0, .1. This is useful for giving a distinct type to a plain value: struct Meters(f64); stops you mixing up meters and seconds by accident.

    Further reading

    • The Rust Book: Defining and instantiating structs
    • The Rust Book: Method syntax
    • The Rust Book: Defining an enum
    • The Rust Book: Derivable traits

    Define a struct Rect with width and height (u32) and three methods taking &self: area(), perimeter() and is_square(). Read rectangles, one per line as width height, and for each print:

    Sample input:

    Sample output:

    A robot starts at position (0, 0) facing north. Model its commands as an enum:

    and the robot as a struct with x, y and a facing field (use another enum Dir with North, East, South, West). Give the robot a method apply(&mut self, cmd: &Command). North increases y, east increases x. Left and Right turn 90 degrees without moving.

    Each input line is F <n>, L or R. Parse each line into a Command, apply it, and finally print x y facing with the direction in lowercase, e.g. 3 -2 south.

    Sample input:

    Sample output:

    struct Player {
        name: String,
        health: i32,
        level: u32,
    }
    
    let mut p = Player {
        name: String::from("Rin"),
        health: 100,
        level: 1,
    };
    p.level += 1;
    println!("{} is level {}", p.name, p.level);
    impl Player {
        fn new(name: &str) -> Player {
            Player { name: name.to_string(), health: 100, level: 1 }
        }
    
        fn is_alive(&self) -> bool {
            self.health > 0
        }
    
        fn take_damage(&mut self, amount: i32) {
            self.health = (self.health - amount).max(0);
        }
    }
    
    let mut hero = Player::new("Rin");
    hero.take_damage(30);
    println!("{}", hero.is_alive()); // true
    #[derive(Debug, Clone, PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let a = Point { x: 1, y: 2 };
    println!("{a:?}");        // Point { x: 1, y: 2 }
    println!("{}", a == a.clone()); // true
    enum Shape {
        Circle(f64),
        Rect { w: f64, h: f64 },
    }
    
    impl Shape {
        fn area(&self) -> f64 {
            match self {
                Shape::Circle(r) => std::f64::consts::PI * r * r,
                Shape::Rect { w, h } => w * h,
            }
        }
    }
    <w>x<h> area=<area> perimeter=<perimeter> square=<true|false>
    3 4
    5 5
    3x4 area=12 perimeter=14 square=false
    5x5 area=25 perimeter=20 square=true
    enum Command {
        Forward(i32),
        Left,
        Right,
    }
    F 5
    R
    F 3
    R
    F 7
    3 -2 south