Custom Types in Rust
Custom Types in Rust
In Rust, custom types allow developers to create more complex data structures that can
encapsulate various forms of data and behavior. This document explores the different ways
to define and use custom types in Rust, including structs, enums, and type aliases.
Understanding how to create and manipulate these types is essential for writing idiomatic
and efficient Rust code.
Custom
Types in
Rust
Structs
Structs are one of the primary ways to create custom types in Rust. They allow you to group
related data together. Here’s how to define and use a struct:
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("Alice"),
age: 30,
};
In this example, we define a Person struct with two fields: name and age. We then create an
instance of Person and print its fields.
Enums
Enums are another powerful feature in Rust that allows you to define a type that can be one
of several variants. This is particularly useful for representing a value that can take on different
forms. Here’s an example:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}
fn main() {
let circle = Shape::Circle(5.0);
let rectangle = Shape::Rectangle(4.0, 6.0);
In this example, we define an enum called Shape with two variants: Circle and Rectangle.
The area function uses pattern matching to calculate the area based on the shape variant.
Type Aliases
Type aliases allow you to create a new name for an existing type, which can improve code
readability. Here’s how to define a type alias:
fn main() {
let distance: Kilometers = 100;
println!("Distance: {} km", distance);
}
In this example, we create a type alias Kilometers for the i32 type. This can make the code
more expressive and easier to understand.
Conclusion
Custom types in Rust, including structs, enums, and type aliases, provide powerful tools for
organizing and managing data. By leveraging these features, developers can create more
readable, maintainable, and efficient code. Understanding how to effectively use custom
types is a fundamental skill for any Rust programmer.