githubEdit

Rust

Attributes

  • Metadata applied to some module, crate, or item;

  • Written as #[attribute];

  • Used to:

    • Conditional compilation of code;

    • Set crate name, version, author, and type (binary or library);

    • Disable lints (warnings);

    • Enable compiler features (macros, glob imports, etc.);

    • Link to a foreign library;

    • Mark functions as unit tests;

    • Mark functions that will be part of a benchmark;

    • Mark the entry point of the program;

    • ...

Some examples:

// `#[derive(Debug)]` automatically implements the `Debug` trait
#[derive(Debug)]
struct Foo {
    a: i32,
    b: i32,
}

// `#[cfg(test)]` marks the following module as a test module
#[cfg(test)
mod tests {
    // `#[test]` marks the following function as a unit test
    #[test]
    fn test_foo() {
        // ...
    }
}

Derive

  • Derive is an attribute;

  • Automatically implements some traits for a type, saving us from writing boilerplate code.

This is equivalent to:

dyn

  • dyn is a keyword used to specify a trait object;

enum vs struct

  • Enums are types that always result in one of a few variants (like an OR);

  • Structs are types that each instance can have different properties (like an AND);

  • Enums are useful for match statements, structs are useful for storing data.

Generics

  • Define any data type, or ones implementing one or more traits;

  • Specified inside angle brackets (<>);

  • Can be used in structs, enums, functions, methods, and impl blocks.

Lifetime

  • Lifetime is the scope for which a variable is valid;

  • A single quote (') is used to specify the lifetime of a variable;

  • Can be generic (declared like a generic type);

  • If not explicitly declared, the compiler infers the lifetime of a variable (implicit).

String vs str

  • String is a mutable, growable heap-allocated string, implemented by a struct wrapping a Vec<u8>;

  • str is an immutable, fixed length string slice.

trait

  • Collection of methods;

  • Contains functions declarations & default implementations;

  • Can be implemented by any type.

Last updated