Start Coding

Rust Structs: Custom Data Types

Structs are a fundamental feature in Rust, allowing developers to create custom data types. They group related data together, providing a way to organize and structure information in your programs.

Defining a Struct

In Rust, you can define a struct using the struct keyword. Here's a simple example:


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

This struct, named Person, has three fields: name, age, and height. Each field has a specific Rust Data Type.

Creating Instances

To create an instance of a struct, you provide values for all its fields:


let alice = Person {
    name: String::from("Alice"),
    age: 30,
    height: 1.75,
};
    

Accessing and Modifying Fields

You can access struct fields using dot notation. If the instance is mutable, you can also modify its fields:


println!("Name: {}", alice.name);
let mut bob = Person {
    name: String::from("Bob"),
    age: 25,
    height: 1.80,
};
bob.age = 26; // Modifying a field
    

Struct Methods

Structs can have associated functions and methods. These are defined in an impl block:


impl Person {
    fn new(name: String, age: u32, height: f64) -> Person {
        Person { name, age, height }
    }

    fn introduce(&self) {
        println!("Hi, I'm {} and I'm {} years old.", self.name, self.age);
    }
}
    

The new function is an associated function, often used as a constructor. The introduce method takes &self as its first parameter, allowing it to access the instance's data.

Struct Update Syntax

Rust provides a convenient way to create a new instance of a struct with most of the values from another instance:


let charlie = Person {
    name: String::from("Charlie"),
    ..bob // Copy the rest of the fields from bob
};
    

Important Considerations

  • Structs are useful for creating domain-specific types in your Rust programs.
  • They help in organizing related data and behavior together.
  • Rust's ownership system applies to structs and their fields.
  • You can implement traits on structs to define shared behavior with other types.

Conclusion

Structs are a powerful feature in Rust, enabling you to create custom types that model your problem domain effectively. They form the basis for object-oriented programming in Rust and are essential for writing clean, organized code.

To learn more about working with structs, explore Rust Methods and Rust Associated Functions.