Menu
×
   ❮   
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Rust Structs


Structs

A struct (short for "structure") is a custom data structure that lets you group related values together.

You can think of a struct like a mini-database for one thing, like a person with a name and age.


Create a Struct

You define a struct using the struct keyword and place the fields (variables) inside:

Example

struct Person {
  name: String,
  age: u32,
  can_vote: bool,
}

Once you have a struct, you can create an object of it.

Then, you can access the fields of the struct using dot syntax (.):

Example

// Create a Struct called Person
struct Person {
  name: String,
  age: u32,
  can_vote: bool,
}

// Create a Person object
let user = Person {
  name: String::from("John"),
  age: 35,
  can_vote: true,
};

// Access and print the values
println!("Name: {}", user.name);
println!("Age: {}", user.age);
println!("Can vote? {}", user.can_vote);
Try it Yourself »

Fields are similar to variables, but they belong to a struct. Since they are part of a larger structure (like Person or Car), they are called fields in Rust, not regular variables.


Change a Field

To change a value inside a struct, you must make the struct object mutable by using mut:

Example

struct Person {
  name: String,
  age: u32,
}

let mut user = Person {
  name: String::from("John"),
  age: 35,
};

user.age = 36; // Change value of age
println!("Name: {}", user.name);
println!("Updated age: {}", user.age);
Try it Yourself »

Why Use Structs?

  • To group related data in a clean way
  • To make your code easier to read and maintain
  • To create real-world examples, like users, books, cars, etc.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.