Compound Types

Structs

`struct`s group and name data of different types.

Definition

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

Construction

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

fn main() {
    let p = Point { x: 1, y: 1 };
}

Side note

It’s common to hide construction behind a call to Point::new() instead of using a raw struct literal.

Field Access

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

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{}", p.x);
    println!("{}", p.y);
}

Tuples

fn main() {
    let p = (1, 2);
    println!("{}", p.0);
    println!("{}", p.1);
}

Tuple Structs

struct Point(i32,i32);

fn main() {
    let p = Point(1, 2);
    println!("{}", p.0);
    println!("{}", p.1);
}

Enums

`enum`s represent different variation of the same subject.

Definition and Construction

enum Direction {
    Right,
    Left,
    Up,
    Down,
}

fn main() {
    let direction = Direction::Left;
}

The different choices of Enums are called "variants."

Enums with Values

enum Movement {
    Right(i32),
    Left(i32),
    Up(i32),
    Down(i32),
}

fn main() {
    let movement = Movement::Left(12);
}

Enums with Structured Variants

enum Actions {
    StickAround,
    MoveTo { x: i32, y: i32},
}

fn main() {
    let action = Actions::MoveTo { x: 0, y: 0 };
}

null

Does not exist.

()

The empty tuple () represents the absence of data.

fn prints_but_returns_nothing(data: &str) -> () {
    println!("passed string: {}", data);
}