This example project will teach you the following concepts:

  1. structs in rust

Step 1: Create Project

The first step is to create a Rust project .

Creating a Project Directory

A good practice is to create a project directory to store your Rust code.

Open a terminal and enter the following commands to make a projects directory and an inner directory for this example within that projects directory.

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir your_example_name
$ cd your_example_name

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir your_example_name
> cd your_example_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Create a file named main.rs.

Rust struct types must be declared before they are used using the struct syntax.

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32
}

Define the main() function:

fn main() {
    let mut mypoint = Point { x: 1, y: 1 };
    let origin = Point { x: 0, y: 0 };

    println!("origin = {:?}", origin);

mypoint is mutable, and its fields as well

    mypoint.y += 1; 
    //origin.y += 1.0; // ERROR: assigning to immutable field

match patterns destructure structs:

    match mypoint {
        Point { x: 0, y: yy } => println!("{}", yy),
        Point { x: xx,  y: yy } => println!("{} {}", xx, yy),
    }

When you are not interested in all the fields of a struct, a struct pattern may end with , (as in Name { field1, }) to indicate that you're ignoring all other fields. Additionally, struct fields have a shorthand matching form that simply reuses the field name as the binding name.

    match mypoint {
        Point { x, .. } => println!("{}", x),
    }
}

Here is the full code:

main.rs


#[derive(Debug)]
struct Point {
    x: i32,
    y: i32
}
fn main() {
    let mut mypoint = Point { x: 1, y: 1 };
    let origin = Point { x: 0, y: 0 };

    println!("origin = {:?}", origin);

    mypoint.y += 1; 
    match mypoint {
        Point { x: 0, y: yy } => println!("{}", yy),
        Point { x: xx,  y: yy } => println!("{} {}", xx, yy),
    }

    match mypoint {
        Point { x, .. } => println!("{}", x),
    }
}

If you run the code here is what you will get:

origin = Point { x: 0, y: 0 }
1 2
1

Run

Save the code and run your code as follows:

Assuming our file name is main.rs, first compile it

$ rustc main.rs

then run it:

$ ./main

On Windows, enter the command .\main.exe instead of ./main:

compile:

> rustc main.rs

then run it:

> .\main.exe