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
This example demonstrates how to use custom struct in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the basics category to build a complete understanding of this topic.