← Retour au cours: Rust from scratch

Structs, methods and impl

Vidéo bientôt disponible

Tuples work for grouping a few values, but when the data has its own meaning (a user, a rectangle, a task) you want to give it names. That is what structs are for: custom types with named fields. With them you model the domain of your program, and with impl blocks you add behavior: methods and associated functions. Rust has no classes, but struct plus impl cover almost everything you need.

Defining and creating a struct

It is defined with the keyword struct, a name in PascalCase and the fields with their type. It is created by writing the name and giving a value to each field in any order. If the variable has the same name as the field you can abbreviate (field init shorthand). With the ..other syntax you copy the remaining fields from another instance. Fields are read with a dot and, if the instance is mut, they can be modified. Important: either the whole struct is mutable or none of it is; there are no individual mutable fields.

rust
#[derive(Debug)]
struct User {
    name: String,
    email: String,
    age: u32,
    active: bool,
}

fn make_user(name: String, email: String) -> User {
    User { name, email, age: 18, active: true } // shorthand for name, email
}

fn main() {
    let mut ana = make_user(String::from("Ana"), String::from("ana@example.com"));
    ana.age = 31;
    println!("{} is {}", ana.name, ana.age);

    let bob = User { name: String::from("Bob"), email: String::from("bob@example.com"), ..ana };
    println!("{:#?}", bob);
}

Methods with impl

An impl block groups the functions of a type. If the first parameter is self, &self or &mut self, it is a method and is called with a dot: rect.area(). Most use &self (read only) or &mut self (modify); self by value consumes the instance and is kept for special cases. Functions without self are called associated functions and are invoked with ::, like String::from. By convention, the constructor is called new. You can have several impl blocks for the same type.

rust
#[derive(Debug)]
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Self { width, height }
    }

    fn square(side: f64) -> Self {
        Self::new(side, side)
    }

    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }

    fn scale(&mut self, factor: f64) {
        self.width *= factor;
        self.height *= factor;
    }
}

fn main() {
    let mut r = Rectangle::new(4.0, 3.0);
    let small = Rectangle::square(2.0);
    println!("area = {}", r.area());
    println!("holds small? {}", r.can_hold(&small));
    r.scale(2.0);
    println!("{:?}", r);
}

Tuple structs and unit structs

There are two more variants. The tuple struct has fields without names and is used to give a distinct type to a tuple: struct Meters(f64) and struct Seconds(f64) cannot be mixed up by mistake, even though both store an f64. It is the technique called newtype. The unit struct has no fields (struct Marker;) and is used when only the type matters, mostly with traits, which you will see in week 6.

rust
struct Meters(f64);
struct Seconds(f64);

fn speed(distance: Meters, time: Seconds) -> f64 {
    distance.0 / time.0
}

fn main() {
    let d = Meters(100.0);
    let t = Seconds(9.58);
    println!("{:.2} m/s", speed(d, t));
    // speed(t, d) would be a compile error: wrong types
}

A frequent question: why do the fields of User use String and not &str? Because we want the struct to own its data. If it stored a reference, it would have to say how long it is valid (a lifetime), a topic for week 6. While you learn, use owned types (String, Vec) in your structs and you will avoid complications. Also, Self is an alias for the type of the impl block: writing it this way makes it easier to rename the type later.

rust
#[derive(Debug)]
struct Counter {
    count: u32,
    step: u32,
}

impl Counter {
    fn new(step: u32) -> Self {
        Self { count: 0, step }
    }
    fn increment(&mut self) {
        self.count += self.step;
    }
    fn value(&self) -> u32 {
        self.count
    }
}

fn main() {
    let mut c = Counter::new(5);
    c.increment();
    c.increment();
    c.increment();
    println!("{}", c.value());
    println!("{:?}", c);
}

Testez vos acquis

Question 1 sur 4

What is a function inside impl without self called?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →