Rust Tuples

🦀 Rust Tuples

Tuples in Rust are fixed-size collections that can hold multiple values of different data types.

They are lightweight, fast, and very commonly used for grouping related values or returning multiple values from a function.


🔹 1. What Is a Tuple?

A tuple:

  • Has fixed length

  • Can store different data types

  • Is stored on the stack (if sizes are known)

  • Uses parentheses ()

fn main() {
let person = ("Sanjit", 22, true);
println!("{}", person.0);
}

🔹 2. Declaring a Tuple

let tup: (&str, i32, bool) = ("Rust", 2024, true);

✔ Type annotation is optional (Rust can infer it)


🔹 3. Accessing Tuple Elements (Indexing)

let t = (10, 3.14, 'A');

println!(“{}”, t.0); // 10
println!(“{}”, t.1); // 3.14
println!(“{}”, t.2); // A

⚠️ Indexing starts from 0


🔹 4. Tuple Destructuring (Very Common)

You can unpack a tuple into variables.

fn main() {
let user = ("Admin", 1, true);
let (role, id, active) = user;

println!(“{}”, role);
println!(“{}”, id);
println!(“{}”, active);
}

✔ Clean
✔ Readable
✔ Idiomatic Rust


🔹 5. Ignoring Values with _

let data = (100, "Rust", false);

let (id, _, status) = data;

println!(“{}”, id);
println!(“{}”, status);

✔ Useful when you don’t need all values


🔹 6. Tuples as Function Return Values

Rust does not support multiple returns, but tuples solve this.

fn calculate(a: i32, b: i32) -> (i32, i32) {
(a + b, a * b)
}
fn main() {
let result = calculate(3, 4);
println!(“Sum={}, Product={}”, result.0, result.1);
}


▶️ Destructuring Function Return

let (sum, product) = calculate(5, 6);
println!("{} {}", sum, product);

🔹 7. Mutable Tuples

You can make a tuple mutable.

fn main() {
let mut t = (1, 2);
t.0 = 10;
t.1 = 20;

println!(“{:?}”, t);
}

⚠️ You cannot change the type or size, only values.


🔹 8. Nested Tuples

let nested = (1, (2, 3), "Rust");

println!(“{}”, (nested.1).0); // 2


🔹 9. Empty Tuple – Unit Type ()

fn demo() {
// returns ()
}
  • () means no value

  • Used when a function returns nothing

  • Similar to void in C/C++


🔹 10. Tuples and Ownership

let t1 = (String::from("Rust"), 10);
let t2 = t1; // ownership moved
// println!(“{:?}”, t1); ❌
println!(“{:?}”, t2);

✔ Ownership rules apply to tuple elements too
✔ If all elements are Copy, tuple is Copy


🔹 11. Tuple vs Array

Feature Tuple Array
Data types Different Same
Size Fixed Fixed
Access .0, .1 [index]
Use case Group values List of values

❌ Common Mistakes

  • Expecting tuples to grow

  • Confusing tuple indexing with arrays

  • Forgetting ownership rules

  • Overusing tuples instead of struct

👉 Use struct when data has meaning and names.


🧠 Key Takeaways

  • Tuples group different types

  • Fixed size, fast, stack-based

  • Excellent for function returns

  • Support destructuring

  • Ownership rules still apply

You may also like...