Day 55 — Moar Rust reading!
26 October 2020 · recurse-center TweetToday I read up on structs, enums, and pattern matching in the Rust book. I also did some rustlings
, and read a lot of Rust blog posts to figure out what I should work on in my last week at RC! I want to build a small project to get more comfortable with Rust.
Structs in Rust seem to work just like C, in the way they encapsulate associated pieces of data together.
struct Point {
x: i32,
y: i32,
}
let origin = Point {
x: 0,
y: 0,
};
Rust also has tuple structs, which look like Python namedtuple
s:
struct Point(i32, i32);
let origin = Point(0, 0);
There are unit structs too, which can be defined with struct Unit;
but I'm not sure how to use them yet.
We can also define methods for a struct using impl
!
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
And then use it on an instantiated struct with rect1.area()
! It looks similar to how we would define methods for a Python class
, the difference being that methods are not defined within a struct.
Rust knows that the type of
self
isRectangle
because it's within theimpl Rectangle
context.
The book mentions that there's no need to separate multiple methods in multiple impl
blocks but that is valid syntax too.
And if we try to print a struct (for debugging purposes) with println!("{}", rect1);
the compiler will throw an error if our struct doesn't implement the Display
trait. That sounds like the __repr__
method in Python.
To solve that, we can "decorate" our struct with #[derive(Debug)]
to add the Debug
trait, and then print it with {:?}
in println!
.
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
}
println!("rect1 is {:?}", rect1);
}
{:#?}
can be use for pretty printing!