- The
UpperCamelCaseconvention is reserved for types and traits - Items that follow the
snake_caseconvention are reserved for attributes, variables, functions, and macros SCREAMING_SNAKE_CASEnames are reserved for constants- Statement is code that does not return any value. Ends with
;. - Expression is code that returns a value. All code blocks will implicitly return their value unless they are a statement.
- Patterns are special syntax that can be used in specific situations.
- Block is a collection of statements and/or expression contained within
{}. Blocks can be treated as the single statement or expression they evaluate to, e.g., blocks can return a value if it’s treated as an expression. - Scope is the concept of whether or not a particular item exists in memory and is accessible at a certain location in our code. The scope of any particular item is limited to the block it is contained in. When a block is closed, all of its values are released from memory and are then considered out-of-scope. If an item is accessible, it is considered in-scope.
- Ignore unused variable warning with
_prefix - All variables are mutable by default. Use
mutkeyword to make it immutable. - Smart pointer behaves like a pointer, but with added capabilities like ownership, automatic cleanup, or reference counting. Use
Boxto allocate data in heap.- You can’t create a trait object directly because traits have no fixed size. Wrapping it in a
Boxsolves this. - Rust requires types to have a known size at compile time. For recursive structures like linked lists or trees, this isn’t possible without indirection.
- You can’t create a trait object directly because traits have no fixed size. Wrapping it in a
Patterns
let (a, b) = 10, "abc";
// Implements Copy, thus copied
let arr = [1, 2, 3];
let [one, two, three] = arr;
// Ownerships are moved to one, two
let arr = [String::from("one"), String::from("two")];
let [one, two] = arr;
// println!("Array: {arr:?}"); // errorCargo commands
cargo new # Create a new Rust projet
cargo build # Compiles our crate
cargo run # Compiles and run crate
cargo doc --open # Build and open our crate's documentation in a web browser Visibility
We can make an item accessible outside of its normal scope by denoting it as public with the pub keyword.
All items in Rust are private by default. Private items can only be accessed within their declared module and any children modules.
See also https://www.codecademy.com/courses/rust-for-programmers/articles/modules-rust
Ownership
The rules that the Rust compiler follows to validate that we do not attempt unsafe behavior are as follows:
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
These rules of ownership have different implications depending on whether our data is stored on the stack or the heap.