Rust Language Reference

repository·master·Indexed 23 days ago

https://github.com/rust-lang/reference

The primary authoritative documentation for the Rust programming language, detailing its grammar, semantics, and language rules. This repository includes the reference content, a developer guide for contributors, and supporting tools such as the grammar parser library, mdbook-spec preprocessor, and the xtask CLI utility.

Tokens
173.2K
Snippets
422
Records
778
Agent score
81%

What's inside rust-lang-reference

  1. What is mdbook-spec

    master

    mdbook-spec is an mdBook preprocessor used to add specialized features to the Rust Language Reference. It automates several documentation tasks including:

    • Grammar Diagrams: Parsing and generating diagrams, automatic grammar production links, and the grammar summary appendix.
    • Standard Library Links: Automatic linking to the Rust standard library.
    • Rule Name Handling: Validating rule names, converting them to links, providing automatic rule link references, generating links to rule tests, and creating the test summary.
    • Admonitions: Support for specialized callout blocks (admonitions).
  2. Use the Diagnostics library for emitting warnings and errors

    master
    The diagnostics library is a basic utility used by Reference tools to emit diagnostic output. It supports emitting both warnings and errors. A key feature is the ability to upgrade all warnings to errors globally using an environment variable, which is useful for strict CI environments or enforcing specific coding standards.
  3. What is a prelude in Rust?

    master

    A prelude is a collection of names (types, functions, macros, etc.) that are automatically brought into the scope of every module in a crate.

    Because these names are implicitly queried during name resolution, they are not members of the module itself. For example, while Box is in scope in every module, you cannot refer to it as self::Box because it is not part of the current module's definition.

  4. What is a trait object and how does it work?

    master

    A trait object is an opaque value of another type that implements a specific set of traits. The set of traits consists of a dyn compatible base trait plus any number of auto traits.

    Trait objects are dynamically sized types (DSTs), meaning their size is not known at compile time because the underlying concrete type is hidden. Consequently, they must be used behind a pointer, such as &dyn SomeTrait or Box<dyn SomeTrait>.

    Each pointer to a trait object contains two components:

    1. A pointer to the instance of the concrete type T.
    2. A virtual method table (vtable), which contains function pointers for each method of the base trait and its supertraits implemented by T. This enables virtual dispatch (late binding), where the specific implementation is determined at runtime.
    trait Printable {
        fn stringify(&self) -> String;
    }
    
    impl Printable for i32 {
        fn stringify(&self) -> String { self.to_string() }
    }
    
    fn print(a: Box<dyn Printable>) {
        println!("{}", a.stringify());
    }
    
    fn main() {
        print(Box::new(10) as Box<dyn Printable>);
    }
  5. Overview of Rust types

    master

    In Rust, every variable, item, and value has a type. The type of a value defines how the memory holding it is interpreted and what operations can be performed on it.

    Types are categorized into several kinds:

    • Primitive types: bool, numeric types (integers and floats), char, str, and the ! (Never) type.
    • Sequence types: Tuples, Arrays, and Slices.
    • User-defined types: Structs, Enums, and Unions.
    • Function types: Functions and Closures.
    • Pointer types: References, Raw pointers, and Function pointers.
    • Trait types: Trait objects and impl Trait.
  6. What is a diverging expression

    master

    A diverging expression is an expression that never completes normal execution. In Rust, these expressions are associated with the ! (never) type. Because they never finish, they can be used in places where a value is expected, as they effectively satisfy any type requirement by never actually providing a value.

    Common examples of diverging expressions include:

    • The panic! macro.
    • The unreachable! macro.
    • Infinite loop expressions.
    • return expressions.
    • break expressions.
    fn diverges() -> ! {
        panic!("This function never returns!");
    }
    
    fn example() {
        let x: i32 = diverges(); // This line never completes.
        println!("This is never printed: {x}");
    }
  7. What is a slice type?

    master

    A slice is a dynamically sized type (DST) that represents a 'view' into a sequence of elements of type T. The syntax for a slice type is [T].

    Because slices are dynamically sized, they are generally used through pointer types rather than directly. Common pointer types for slices include:

    • &[T]: A 'shared slice' (often just called a 'slice'). It borrows the data it points to without owning it.
    • &mut [T]: A 'mutable slice'. It mutably borrows the data it points to.
    • Box<[T]>: A 'boxed slice', which owns the slice on the heap.
  8. Overview of Rust loop expressions

    master

    Rust provides four primary loop expressions for different control flow needs:

    1. loop: An infinite loop that repeats its body continuously.
    2. while: A predicate loop that repeats as long as a condition remains true.
    3. for: An iterator loop that extracts values from an implementation of std::iter::IntoIterator.
    4. Labeled block expressions: A block that runs exactly once but allows early exit using break with a label.

    Key Capabilities:

    • break: Supported by all four types to terminate execution.
    • continue: Supported by all except labeled block expressions to skip to the next iteration.
    • Evaluation to values: Only loop and labeled block expressions can evaluate to non-trivial values (via break).
  9. Understand Crate structure and compilation

    master

    A crate is the fundamental unit of compilation and linking in Rust.

    • Types: Crates can be libraries or executables.
    • External Crates: Crates can link to and refer to other library crates.
    • Module Tree: Every crate has a self-contained tree of modules, starting from an unnamed root module called the crate root.
    • Visibility: Items can be made visible to other crates by marking them as public in the crate root, including through the paths of public modules.