RRust By Example
beginnerBasics

Custom Struct

Define and instantiate a custom struct with named fields.

Custom Struct

Define and instantiate a custom struct with named fields.

Difficulty

Beginner

Code

rust
struct User {
    name: String,
    age: u32,
    email: String,
}

fn main() {
    let user = User {
        name: String::from("Alice"),
        age: 30,
        email: String::from("alice@example.com"),
    };
    println!("{} is {} years old", user.name, user.age);
}

Explanation

Structs group related data. Fields are accessed with dot notation. String::from creates owned strings.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples