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