Compound data types let you group multiple values together in one place. This helps keep related data organized and easy to use.
0
0
Compound data types in Rust
Introduction
When you want to store a person's name, age, and height together.
When you need to keep track of a point's x and y coordinates.
When you want to group different types of data into one variable.
When you want to return multiple values from a function.
When you want to create a simple record or structure for your data.
Syntax
Rust
let tuple_name: (type1, type2, type3) = (value1, value2, value3);
struct StructName {
field1: Type1,
field2: Type2,
field3: Type3,
}
let instance = StructName {
field1: value1,
field2: value2,
field3: value3,
};Rust has two main compound types: tuples and structs.
Tuples group values by position, structs group values by named fields.
Examples
This tuple holds a name, age, and height together.
Rust
let person: (&str, u8, f32) = ("Alice", 30, 5.5);
This struct defines a point with x and y coordinates.
Rust
struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };Tuples can hold different types of values together.
Rust
let mixed = ("hello", 42, true);
Sample Program
This program shows how to use a struct to store a person's data and a tuple to store point coordinates. It prints each value clearly.
Rust
struct Person {
name: String,
age: u8,
height: f32,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
height: 5.5,
};
println!("Name: {}", alice.name);
println!("Age: {}", alice.age);
println!("Height: {}", alice.height);
let point: (i32, i32) = (10, 20);
println!("Point coordinates: ({}, {})", point.0, point.1);
}OutputSuccess
Important Notes
Tuples have fixed size and types, you cannot add or remove elements.
Struct fields are accessed by name, tuples by position using .0, .1, etc.
Use structs when you want clearer code with named fields.
Summary
Compound data types group multiple values into one variable.
Rust uses tuples and structs as main compound types.
Tuples are simple and use positions, structs use named fields for clarity.