Build your own Paint
Follow with gitGoing further
EN/FR
01

Chapter 1 / 11

2D vectors

We write a Vec2 type with its operations, and try it out in the terminal.

Duration45 min
Concepts
  • struct
  • impl
  • derive
  • Copy
  • operator traits
  • Display
  • Result
  • Option
  • slices

In a drawing app, you spend your time handling positions: where the mouse is, where a rectangle starts, where the center of a circle is. You also handle sizes and movements. All of these are pairs of numbers, an x and a y.

We could make do with (f32, f32) tuples, but we'll soon want to add two positions together, compute a distance or multiply a movement by a number. Rather than rewriting those calculations everywhere, we'll create our own type, Vec2, and teach it these operations.

This chapter happens entirely in the terminal, no graphics yet. It's a chance to see Rust's basic building blocks on a simple example: structs, methods, traits, and the two types you'll run into everywhere, Option and Result.

A struct#

We put our type in its own file. Create src/vec2.rs:

src/vec2.rsRust
/// A 2D vector, used for positions and sizes on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

A struct groups several values under one name. Ours has two fields, x and y, which are 32-bit floating-point numbers (f32). The /// lines above are documentation comments: they show up when you hover over the type in your editor.

In Rust, everything is private by default. The pub in front of struct makes the type usable outside this file, and the pub in front of each field lets the rest of the program read and change x and y.

The #[derive(...)] line asks the compiler to write some code for us:

  • Debug lets us print a Vec2 with {:?}, handy for debugging.
  • PartialEq lets us compare two Vec2 values with ==.
  • Clone and Copy let us copy a Vec2 freely. This matters more than it seems, we'll come back to it a bit further down.

For now, main.rs doesn't know this file exists. We need to declare it with mod, then import the type with use:

src/main.rsRust
mod vec2;

use vec2::Vec2;

fn main() {
    let a = Vec2 { x: 3.0, y: 4.0 };
    println!("{:?}", a);
}

Run cargo run, and the program prints:

Output
Vec2 { x: 3.0, y: 4.0 }

mod vec2; tells Rust: there's a module called vec2, go find it in src/vec2.rs. Each file is a module, and that's how a Rust program is split up.

Methods#

Writing Vec2 { x: 3.0, y: 4.0 } every time will quickly get tedious. We add an impl block, which holds everything we can do with a Vec2:

src/vec2.rsRust
// ...

impl Vec2 {
    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };

    pub fn new(x: f32, y: f32) -> Vec2 {
        Vec2 { x, y }
    }

    pub fn dot(self, other: Vec2) -> f32 {
        self.x * other.x + self.y * other.y
    }
}

ZERO is a constant associated with the type: we use it as Vec2::ZERO.

new is an associated function. It doesn't apply to an existing vector, it makes one, and we call it with Vec2::new(3.0, 4.0). The name new isn't special in Rust, it's just the convention. Notice Vec2 { x, y } too: when a variable has the same name as the field, there's no need to write x: x.

dot is a method, because its first parameter is called self. We call it with a dot: a.dot(b). It computes the dot product of the two vectors. We'll use it in chapter 7 to tell whether the mouse is on a line.

Your turn

Add a length method that returns the length of the vector. The length of a vector (x, y) is √(x² + y²), and x² + y² is precisely the dot product of the vector with itself. In Rust, the square root of an f32 is written number.sqrt().

src/vec2.rsRust
impl Vec2 {
    // ...

    pub fn length(self) -> f32 {
        todo!()
    }
}

todo!() is a macro that lets the code compile even though the function isn't written yet. If it gets called, the program stops with a "not yet implemented" message. Handy for moving forward piece by piece.

Solution
src/vec2.rsRust
pub fn length(self) -> f32 {
    self.dot(self).sqrt()
}

We reuse dot rather than writing out self.x * self.x + self.y * self.y again. It's the same calculation, and the formula stays written in a single place.

Rust behavior

Look at the solution for length: self.dot(self) uses self twice. That only works because Vec2 is Copy.

By default, when you pass a value to a function, Rust moves it: the function becomes its owner, and the old variable can no longer be used. This is the basis of Rust's ownership system, the thing that lets it free memory without a garbage collector. Remove Copy from the derive and the compiler refuses right away:

Compiler error
error[E0382]: use of moved value: `self`
   |
22 |     pub fn length(self) -> f32 {
   |                   ---- move occurs because `self` has type `Vec2`, which does not implement the `Copy` trait
23 |         self.dot(self).sqrt()
   |              ----^^^^-
   |              |   |
   |              |   value used here after move
   |              `self` moved due to this method call

The first self is moved into the call to dot, so the second one no longer exists. With Copy, Rust copies the value instead of moving it, and the original stays usable. It's the right choice for a small type like Vec2: copying two f32 values is 8 bytes, it costs nothing. For a big value, like an image that can range from several KB to several MB, we'll do things differently: we'll lend it with & instead of copying it.

Operators#

We'd like to write a + b to add two vectors, like we do with numbers. In Rust, operators are traits: + corresponds to the Add trait, - to Sub, * to Mul. A trait is a set of methods that a type can implement. If we implement Add for Vec2, we get +.

At the top of src/vec2.rs, import the trait, then add its implementation:

src/vec2.rsRust
use std::ops::Add;

// ...

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, other: Vec2) -> Vec2 {
        Vec2::new(self.x + other.x, self.y + other.y)
    }
}

type Output = Vec2; says what the addition returns. Here, a vector plus a vector gives a vector, but that's not required: the trait leaves the choice to us.

Your turn

Write impl Sub for Vec2, so we can write a - b. It's almost the same as Add.

Solution
src/vec2.rsRust
use std::ops::{Add, Sub};

// ...

impl Sub for Vec2 {
    type Output = Vec2;
    fn sub(self, other: Vec2) -> Vec2 {
        Vec2::new(self.x - other.x, self.y - other.y)
    }
}

You need to import Sub next to Add. The method of the Sub trait is called sub, and the one of Add is called add. Nothing else changes.

One last operator: multiplying a vector by a number, to scale a movement up or down. This time, we don't multiply a Vec2 by a Vec2 but by an f32. We say so between angle brackets:

src/vec2.rsRust
use std::ops::{Add, Mul, Sub};

// ...

impl Mul<f32> for Vec2 {
    type Output = Vec2;
    fn mul(self, k: f32) -> Vec2 {
        Vec2::new(self.x * k, self.y * k)
    }
}

We can now write a * 2.0. Careful, 2.0 * a doesn't work: we'd need to implement Mul<Vec2> for f32, which is possible but we won't need it.

Printing a vector#

{:?} prints Vec2 { x: 3.0, y: 4.0 }, which is fine for debugging but a bit verbose. To print simply (3, 4) with {}, we need to implement the Display trait:

src/vec2.rsRust
use std::fmt;
use std::ops::{Add, Mul, Sub};

// ...

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

The signature looks a bit scary the first time, but it's always the same: you can copy it as is for any type. The only line that matters is the write! one, which works like println! but writes into f instead of the terminal.

Notice that the numbers are printed without .0: an f32 that equals 3.0 prints as 3 with {}, but as 3.0 with {:?}.

An operation that can fail#

Normalizing a vector means keeping its direction but bringing its length down to 1, by dividing x and y by the length. Except the zero vector (0, 0) has a length of 0, and dividing by zero makes no sense.

In many languages, you'd throw an exception. In Rust, a function that can fail says so in its return type, with Result:

src/vec2.rsRust
impl Vec2 {
    // ...

    /// Returns a vector of length 1 pointing in the same direction.
    /// Fails for the zero vector, which has no direction.
    pub fn normalize(self) -> Result<Vec2, String> {
        let len = self.length();
        if len == 0.0 {
            Err(String::from("cannot normalize the zero vector"))
        } else {
            Ok(Vec2::new(self.x / len, self.y / len))
        }
    }
}

Result<Vec2, String> means: either it works and we get a Vec2, wrapped in Ok, or it fails and we get an error message, wrapped in Err. Whoever calls normalize can't get the vector out without checking which of the two they received. The compiler forces it, so you can't forget the error case.

To look inside, we use match:

src/main.rsRust
match a.normalize() {
    Ok(n) => println!("a normalized = {n}"),
    Err(e) => println!("error: {e}"),
}

Each arm gives a name to what's inside (n or e) and uses it. By the way, {n} in the text prints the variable n directly, it's a shortcut for println!("{}", n).

A value that may be missing#

Last function of the chapter: finding the longest vector in a list. This one doesn't go in the impl block, since it doesn't apply to one vector in particular. It's a free function of the module:

src/vec2.rsRust
/// Returns the longest vector of the slice, or `None` if it is empty.
pub fn longest(points: &[Vec2]) -> Option<Vec2> {
    let mut best: Option<Vec2> = None;
    for &p in points {
        match best {
            Some(b) if b.length() >= p.length() => {}
            _ => best = Some(p),
        }
    }
    best
}

There's quite a lot of new stuff in these few lines.

&[Vec2] is a slice: a view onto a run of Vec2 values stored side by side, whether they come from an array or a Vec. The & means we borrow the list to read it, without taking it away from whoever passed it to us.

And what if the list is empty? Then there's no longest vector. That's what Option is for: Some(v) when there's a value, None when there isn't. Rust has no null. A value that may be missing has the type Option, and as with Result, the compiler forces you to handle both cases.

In the loop, for &p in points goes through the slice. Each element comes as a reference &Vec2, and &p "unwraps" it to get a Vec2 directly, which is possible because it's Copy.

Finally, the match has a condition: Some(b) if b.length() >= p.length() only matches if we already have a best candidate and it's at least as long as p. In that case, we do nothing ({}). In every other case (_), either because we have nothing yet or because p is longer, p becomes the new best.

Putting it all together#

Here's the full main.rs, which tries out everything we just wrote. The use now also imports the longest function:

src/main.rsRust
mod vec2;

use vec2::{Vec2, longest};

fn main() {
    let a = Vec2::new(3.0, 4.0);
    let b = Vec2::new(1.0, 2.0);

    println!("a = {a}, b = {b}");
    println!("a + b = {}", a + b);
    println!("a - b = {}", a - b);
    println!("a * 2 = {}", a * 2.0);
    println!("a . b = {}", a.dot(b));
    println!("|a| = {}", a.length());

    match a.normalize() {
        Ok(n) => println!("a normalized = {n}"),
        Err(e) => println!("error: {e}"),
    }
    match Vec2::ZERO.normalize() {
        Ok(n) => println!("zero normalized = {n}"),
        Err(e) => println!("error: {e}"),
    }

    match longest(&[a, b]) {
        Some(p) => println!("longest = {p}"),
        None => println!("no points"),
    }
    println!("longest of nothing = {:?}", longest(&[]));
}
Terminal
cargo run

The program prints:

Output
a = (3, 4), b = (1, 2)
a + b = (4, 6)
a - b = (2, 2)
a * 2 = (6, 8)
a . b = 11
|a| = 5
a normalized = (0.6, 0.8)
error: cannot normalize the zero vector
longest = (3, 4)
longest of nothing = None

The vector (3, 4) has a length of 5, the 3-4-5 triangle from school. Handy for checking that length is right.

The full src/vec2.rs file
src/vec2.rsRust
use std::fmt;
use std::ops::{Add, Mul, Sub};

/// A 2D vector, used for positions and sizes on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };

    pub fn new(x: f32, y: f32) -> Vec2 {
        Vec2 { x, y }
    }

    pub fn dot(self, other: Vec2) -> f32 {
        self.x * other.x + self.y * other.y
    }

    pub fn length(self) -> f32 {
        self.dot(self).sqrt()
    }

    /// Returns a vector of length 1 pointing in the same direction.
    /// Fails for the zero vector, which has no direction.
    pub fn normalize(self) -> Result<Vec2, String> {
        let len = self.length();
        if len == 0.0 {
            Err(String::from("cannot normalize the zero vector"))
        } else {
            Ok(Vec2::new(self.x / len, self.y / len))
        }
    }
}

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, other: Vec2) -> Vec2 {
        Vec2::new(self.x + other.x, self.y + other.y)
    }
}

impl Sub for Vec2 {
    type Output = Vec2;
    fn sub(self, other: Vec2) -> Vec2 {
        Vec2::new(self.x - other.x, self.y - other.y)
    }
}

impl Mul<f32> for Vec2 {
    type Output = Vec2;
    fn mul(self, k: f32) -> Vec2 {
        Vec2::new(self.x * k, self.y * k)
    }
}

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

/// Returns the longest vector of the slice, or `None` if it is empty.
pub fn longest(points: &[Vec2]) -> Option<Vec2> {
    let mut best: Option<Vec2> = None;
    for &p in points {
        match best {
            Some(b) if b.length() >= p.length() => {}
            _ => best = Some(p),
        }
    }
    best
}

Exercises#

  1. Implement the Neg trait (in std::ops) so you can write -a, which flips the direction of the vector.

  2. Write a function distance(a: Vec2, b: Vec2) -> f32 that returns the distance between two points. Try to write it in one line with what we already have.

Solutions

1. Same idea as Add, but with a single operand:

src/vec2.rsRust
use std::ops::{Add, Mul, Neg, Sub};

impl Neg for Vec2 {
    type Output = Vec2;
    fn neg(self) -> Vec2 {
        Vec2::new(-self.x, -self.y)
    }
}

2. The distance between two points is the length of the vector going from one to the other:

src/vec2.rsRust
pub fn distance(a: Vec2, b: Vec2) -> f32 {
    (b - a).length()
}

Recap#

  • A struct groups fields together, and an impl block gives it associated functions (Vec2::new) and methods (a.dot(b)).
  • #[derive(...)] makes the compiler write code for you: debug printing, comparison, copying.
  • By default, passing a value moves it. A small type can be Copy so it gets copied instead.
  • Operators and printing are traits (Add, Sub, Mul, Display) that we implement for our own types.
  • Result is for things that can fail, Option for things that may be missing, and match forces you to handle every case.
Following along with git?

This chapter matches the tag ch01-vec2.

In chapter 2, we make our first image: an array of pixels in memory, saved to a file you can open with any image viewer.

On this page

  1. A struct
  2. Methods
  3. Operators
  4. Printing a vector
  5. An operation that can fail
  6. A value that may be missing
  7. Putting it all together
  8. Exercises
  9. Recap
← PreviousChapter 0SetupContentsNext →Chapter 2An image in memory

Build your own Paint

A tutorial by theZackD

The code on GitHubFound a mistake? Open an issueCode under the MIT license