Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

data structures
data type

How to use structs in Rust

Educative Answers Team

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.


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
        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;
// Assign a new value to the name field = 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


data structures
data type
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring