Skip to main content

Tuples

A tuple in Rust is a fixed-size collection of values that can hold multiple data types at the same time.

Think of a tuple as:

“A lightweight way to group related values together.”

let person = ("Alice", 25, 5.6);
  • "Alice"&str
  • 25i32
  • 5.6f64

A single variable stores multiple values of different types.

Key Characteristics of Tuples

FeatureTuple
SizeFixed
Data typesCan be different
MemoryStack (usually)
IndexingNumeric
MutabilityOptional
OwnershipOwns values

Tuple Type Annotation

let info: (&str, i32, f64) = ("Bob", 30, 6.1);

Syntax: (type1, type2, type3)

Accessing Tuple Elements

Using Dot Notation

let point = (10, 20);

println!("{}", point.0); // 10
println!("{}", point.1); // 20

Indexing starts from 0.

Mutable Tuples

let mut stats = (100, 200);

stats.0 = 150;
stats.1 = 250;

Entire tuple must be mutable to change elements.

Destructuring Tuples (Very Important)

Basic Destructuring

let user = ("Alice", 25);

let (name, age) = user;

Extracts values into separate variables.

Partial Destructuring

let (name, _) = ("Bob", 30);

_ ignores unwanted values.

Destructuring in let

let (x, y, z) = (1, 2, 3);

Tuples in Functions

Returning Multiple Values

Rust uses tuples instead of multiple return values.

fn calculate(a: i32, b: i32) -> (i32, i32) {
(a + b, a * b)
}

Usage:

let result = calculate(3, 4);
println!("Sum: {}, Product: {}", result.0, result.1);

Destructuring Return Values

let (sum, product) = calculate(3, 4);

Tuples vs Arrays

FeatureTupleArray
TypesMultipleSame
SizeFixedFixed
Index.0, .1[i]
Use caseMixed dataSame-type data

Use tuples when:

  • Values are logically related
  • Types differ
  • Data grouping is temporary

Unit Tuple ()

let x = ();
  • Called the unit type
  • Represents “no value”
  • Similar to void in other languages

Functions Returning ()

fn print_message() {
println!("Hello Rust");
}

If no return value is specified, Rust returns ().

Nested Tuples

let data = ((1, 2), ("A", "B"));

Access:

println!("{}", data.0.1); // 2
println!("{}", data.1.0); // A

Pattern Matching with Tuples

let point = (0, 5);

match point {
(0, y) => println!("On Y axis at {}", y),
(x, 0) => println!("On X axis at {}", x),
(x, y) => println!("Point at ({}, {})", x, y),
}

Extremely useful in real Rust programs.

Memory and Ownership Notes

  • Tuples own their data
  • Ownership rules apply element-wise
  • Large tuples may be moved instead of copied
let t1 = (String::from("Hi"), 10);
let t2 = t1; // t1 moved