[フレーム]

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.

New

W3Schools Adventure App

Coding fundamentals as a game. Bite-sized lessons and challenges.

Ready to start your journey? Your streak is waiting.
+60 XP
W3Schools Adventure tutor
W3Schools Adventure map
×

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

FORUM ABOUT ACADEMY
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, cookies and privacy policy.

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

AltStyle によって変換されたページ (->オリジナル) /