Trusted answers to developer questions

How to use structs in Rust

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

A struct is a user-defined data type that contains fields which define its particular instance. Structs help programmers implement abstract ideas in a more understandable fashion. For example, creating a Student struct that consists of an id, name, marks, etc. makes the code more readable.

Syntax

In Rust, a struct is defined in the following way:

struct Student {
    id: i32,
    name: String,
    marks: i8,
}

The type of each field is written in front of its name (e.g., id is of type i32, name is a String, and so on).

Creating instances

Structs are initialized in the same way as they are declared except that the value of a field is written in place of its type, a semi-colon is placed after the closing }, and the struct keyword isn’t used.

The instance is caught in a variable so that it can be used later. Also, note that the fields to be initialized do not need to be in the order in which they were defined:

// Create a mutable struct:
let mut s1 = Student {
    id: 100,
    marks: 45, // Marks set before name
    name: String::from("Charlie"),
}; // Semi-colon.
svg viewer

Shorter notation

If a field of a struct is initialized using a variable with the same name as the field itself, then a shorter syntax can be used:

fn create_and_return(id: i32, name: String, m: i8) {
    // Create a struct and return it:
    Student {
        id, // Equivalent to id: id
        name,
        marks: m,
    }
}

Getting values

The value of a struct’s particular field can be retrieved using the dot notation. It can also be changed if it is a mutable variable:

// Retrieve the name of s1
s1.name;
// Assign a new value to the name field
s1.name = String::from("Sally");

Another shortcut

If some or all fields of a struct must have the same values as a previously declared struct, then instead of separately assigning values to each field, the following syntax can be used:

let s2 = Student {
    id: 200,
    ..s1 // Set remaining attributes equal to s1's attributes
};

RELATED TAGS

data structures
data type
fields
tuple
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?