Programming Rust, 3rd Edition
Notes
Preface
No Notes.
Chapter 01: Systems Programmers Can Have Nice Things
No notes.
Chapter 02: A Tour of Rust
- Man, right off the rip I love how everything is built into
cargo. No messing around with make files.cargo new program,cargo run,cargo cleanlove it. #[test]is an example of an attribute. Attributes are an open-ended system for marking functions and other declarations with extra information. They’re used to control compiler warnings and code style checks, include code conditionally (like#ifdefin C) and tell Rust how to interact with code written in other languages.assert_eq!is a macro,!character marks macro calls and are “expanded” to Rust code at compile time.- A trait is a collection of function signatures that types can implement. Any type that implements the
FromStrtrait has afrom_strmethod that tries to prase a value of that type from a string.
A trait must be in scope to use its methods even though you never the trait name anywhere else in the program.
- What is interesting as well from
u64is that it’s a type that implements a method to conform to theFromStrtrait. Think of this similar to static methods on classes in traditional OOP.
expect()is a method on theResulttype where if the result isErr(e)it will print a message that includes a description ofeand exits the program. Otherwise if the result isOk(v)is simply returnsvitself.&numbers[1..]borrows a reference to the vector’s elements from the second onward.*mdereferencesm, yielding the value it refers to. Sincenumbersowns the vector, Rust automatically frees it whennumbersgoes out fo scope at the end ofmain.
||is Rust closure expression. A closure is a value that can be called as if it were a function.I think my biggest takeaway so from Rust is that it takes the unspoken rules and general guidelines from C & C++ and makes those rules explicit and enforced by the compiler so the programmers intent on how to use something is enforced.
Okay Rust enums were tripping me up at first because I was treating
Noneas a specific Rust keyword but it’s a variant in theOption<T>which is a generic enum type takes in a type T and returns eitherNoneorSome(T). NowSomewas confusing to me because wonder why can’t I just doNoneorTthinking in terms of TypeScript unions like null | T. This wasn’t the right way to think of about it. Instead it’s more like a TypeScript discriminated union e.g.This made it click for me.
The unit type for Rust
()is akin tovoidin Cahhhhh so
?is just syntax sugar for
Chapter 03: Fundamental Types
usizeandisizeare analogous tosize_tandptrdiff_tin C.- Rust’s
chartype is a Unicode character type, not an integer type, and is quite different from C’schar. You can useu8type for byte values. - When indexing into a slice you have to use a
usizevalue - Array’s lengths are fixed at compile time.
[0u8: 1024]is a one kb buffer filled with zeros. - Rust has no notation for an uninitialized array and in general rust ensures that code can never access uninitialized memory.
- The benefit of arrays (given their limitations) is they are efficient: small arrays can be stored on the stack or inside a struct without allocating more heap memory.
- For lists with variable length use a vector.
- Vector’s contain three values:
- A pointer to a heap-allocated buffer
- number of elements that buffer has the capacity to store
- number of elements that is actually contains now (its length)
- When the buffer has reached capacity adding another element to the vector entails allocating a larger buffer, copying the present contents into it, updating the vector’s pointer and capacity to describe the new buffer and freeing the old one.
Vec::with_capacityallows you specific the capacity at creation time.Vecis an ordinary type defined in Rust and is not built into the language.- A slice written
[T]without specifying the length, is a region of an array or vector. - Slices are always passed by reference.
- A slice reference is a fat pointer: a two-word value comprising a pointer to the slice’s first element and the number of elements in the slice.
Chapter 04: Ownership and Moves
This is nice convenient method:
```rust let first_name = composers[0].name.take(); // same as let first_name = std::mem:replace(&mut composers[0].name, None);
Wow, it’s surprising to me hear that when you move ownership the original owner variable is actually uninitialized.
For user defined types like
enumorstructsyou have to implement theCopyandClonetraits for the value to be copied instead of moved. If you type only includes values that are already copyable you can use the#[derive(Copy, Clone)]attribute where the compiler will generate the Rust code for you to implement this traits.
Chapter 05: References
- Very interesting to see how Rust handles refs and derefs for you. I can traverse refs of refs of refs all the way to the value without making you deref. Works for comparison operators and struct field access.
- If you do want to compare if two refs actually point to the same memory address you can use
std::ptr::eq() - Key Rust ref rules:
- can never be
null - you can’t use any variable until it’s been initialized
- can’t convert integers to references e.g. zero into a reference (outside of
unsafecode) - In many places where a nullptr was traditional used Rust recommends using
Option<&T>
- can never be