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:
/// 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:
Debuglets us print aVec2with{:?}, handy for debugging.PartialEqlets us compare twoVec2values with==.CloneandCopylet us copy aVec2freely. 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:
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:
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:
// ...
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.
Solution
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.
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:
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.
Solution
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:
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:
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:
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:
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:
/// 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:
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(&[]));
}cargo runThe program prints:
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 = NoneThe 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
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#
-
Implement the
Negtrait (instd::ops) so you can write-a, which flips the direction of the vector. -
Write a function
distance(a: Vec2, b: Vec2) -> f32that 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:
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:
pub fn distance(a: Vec2, b: Vec2) -> f32 {
(b - a).length()
}Recap#
- A
structgroups fields together, and animplblock 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
Copyso it gets copied instead. - Operators and printing are traits (
Add,Sub,Mul,Display) that we implement for our own types. Resultis for things that can fail,Optionfor things that may be missing, andmatchforces you to handle every case.
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.