Rust By Example

repository·master·Indexed 27 days ago

https://github.com/rust-lang/rust-by-example

An educational resource for learning the Rust programming language through runnable code examples. It features interactive learning via a live code editor and covers core language concepts including attributes, conditional compilation with #[cfg] and cfg!, Cargo package management, dependency configuration, and testing strategies.

Tokens
94.2K
Snippets
245
Records
326
Agent score
93%

What's inside Rust By Example

  1. Overview of standard library (std) types

    master

    The Rust standard library (std) provides several custom types that extend the functionality of basic primitives. Key types include:

    • Growable Strings: e.g., String (for text like "hello world")
    • Growable Vectors: e.g., Vec<T> (for collections like [1, 2, 3])
    • Optional Types: Option<T> (used for values that may or may not be present)
    • Error Handling Types: Result<T, E> (used for operations that can succeed or fail)
    • Heap Allocated Pointers: Box<T> (for managing data on the heap)
  2. Overview of Cargo package management

    master

    Cargo is the official Rust package management tool. It provides several key features for Rust development:

    • Dependency management: Integrates with crates.io, the official Rust package registry.
    • Test awareness: Automatically handles and runs unit tests.
    • Benchmark awareness: Manages and runs benchmarks.

    For comprehensive documentation and advanced usage, refer to The Cargo Book.

  3. Understand Associated Items in Traits

    master

    Associated items are an extension to trait generics that allow a trait to internally define new items. This mechanism enables traits to define types or constants that are tied to the specific implementation of that trait for a given type.

    A common use case is an associated type, which provides simpler usage patterns when a trait is generic over its container type, avoiding the need to repeat generic parameters throughout the code.

  4. Explore Rust type mechanisms

    master

    Rust provides several mechanisms to define or change the types of primitive and user-defined types. You can manage types through:

    • Casting: Converting between primitive types.
    • Literals: Specifying the desired type of a literal value.
    • Type inference: Allowing the compiler to determine types automatically.
    • Aliasing: Creating type aliases for existing types.
  5. Understand Rust testing styles

    master

    Rust provides built-in support for software testing through three primary styles:

    • Unit testing: Testing individual components or functions in isolation.
    • Doc testing: Running code examples found within documentation to ensure they remain correct and functional.
    • Integration testing: Testing how different parts of a library or application work together as a whole.
  6. Understand Rust crates and compilation units

    master

    In Rust, a crate is the fundamental compilation unit. When you run rustc some_file.rs, some_file.rs is treated as the crate file.

    Key behaviors:

    • Module Integration: Modules are not compiled individually. If a crate file contains mod declarations, the contents of the referenced module files are inserted into the crate file at the location of the declarations before the compiler runs.
    • Compilation Target: A crate can be compiled into either a binary or a library.
    • Default Behavior: By default, rustc produces a binary.
  7. Understand the difference between `String` and `&str`

    master

    Rust uses two primary string types:

    • String: A heap-allocated, growable, and not null-terminated vector of bytes (Vec<u8>) that is guaranteed to be valid UTF-8.
    • &str: A string slice (&[u8]) that points to a valid UTF-8 sequence. It acts as a view into a String or a string literal, similar to how &[T] views a Vec<T>.
    fn main() {
        // A reference to a string allocated in read only memory
        let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
    
        // Create an empty and growable `String`
        let mut string = String::new();
        string.push('a');
        string.push_str(", ");
    
        // Heap allocate a string
        let alice = String::from("I like dogs");
        // Allocate new memory and store the modified string there
        let bob: String = alice.replace("dog", "cat");
    }
  8. Understand the Rust module system

    master

    Rust uses a module system to hierarchically organize code into logical units called modules. This system allows you to manage visibility (controlling which items are public or private) and group related items together. A module can contain various items, including:

    • Functions
    • Structs
    • Traits
    • impl blocks
    • Other modules
  9. Understand File I/O error handling with the File struct

    master
    The File struct provides read and/or write access to an opened file by wrapping a file descriptor. Because file I/O operations are prone to failure, all File methods return the io::Result<T> type. This is a type alias for Result<T, io::Error>, which forces explicit handling of all potential failure paths.
  10. Understand Scoping rules in Rust

    master

    In Rust, scopes determine the lifecycle of variables and the validity of borrows. Scopes are used by the compiler to manage:

    • Ownership: When resources are created or destroyed.
    • Borrowing: When borrows (references) are considered valid.
    • Lifetimes: The duration for which a reference remains valid.