Rust

Useful resources for learning Rust:

Installation

curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

Getting Started

As tradition dictates, the first thing to learn in Rust is how to write hello world: 2

File hello.rs:

fn main() {
    println!("Hello, world!");
}

Compile and run:

rustc hello.rs && ./hello

Expected output:

Hello, world!

Structs

Conventional way of defining a struct is to use the struct keyword:

struct Point {
    x: i32,
    y: i32,
}

Conventional way of initializing an instance of a struct:

fn main() {
    let origin = Coord { x: 0, y: 0 };
    println!("The origin is at ({}, {})", origin.x, origin.y);
}

Rust has a syntax called init field shorthand which allows structs to be initialized in a more terse syntax. You can provide the name of an identifier in place of any field: value, pairs, for any variable whose identifier is a field within a struct.

Struct Coord {
    x: i32,
    y: i32,
}

fn location(x: i32, y: i32) -> Coord {
    Coord { x, y }
}

Rust allows you to use struct update syntax to instantiate a new struct using the values of an existing struct.

fn main() {
    let worker = Worker {
        name: "Tommy",
        occupation: "Software Engineer",
        organization: "USC",
    };
    let colleague = Worker { name: "Tina", ..worker };

From the documentation:

The &lbracket;..worker&rbracket; must come last to specify that any remaining fields should get their values from the corresponding fields in &lbracket;..worker&rbracket;

Miscellaneous Notes

Integer Literal Separator

You can use _ to separate digits within integer literals, such as 1000000. For example:

let million = 1_000_000;

The Unit Type

The () tuple, without any values, is a special type, known as the unit type and its value is the unit value.

You can define a struct without fields, known as a unit-like struct, because it contains the unit-type tuple, which contains zero elements. For example:

struct Value;

fn main() {
    let a = Unit;
    let b = Unit;
    assert_eq!(a, b);
}

Documentation

When programming in Rust, you can embed documentation comments within your code. The Rust Programming Language also covers this in an additional section: Making Useful Documentation Comments.


sysroot

Configuration settings for Visual Studio Code's rust-analyzer extension: