Rust Tuples
🦀 Rust Tuples
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
()
🔹 2. Declaring a Tuple
✔ Type annotation is optional (Rust can infer it)
🔹 3. Accessing Tuple Elements (Indexing)
⚠️ Indexing starts from 0
🔹 4. Tuple Destructuring (Very Common)
You can unpack a tuple into variables.
✔ Clean
✔ Readable
✔ Idiomatic Rust
🔹 5. Ignoring Values with _
✔ Useful when you don’t need all values
🔹 6. Tuples as Function Return Values
Rust does not support multiple returns, but tuples solve this.
▶️ Destructuring Function Return
🔹 7. Mutable Tuples
You can make a tuple mutable.
⚠️ You cannot change the type or size, only values.
🔹 8. Nested Tuples
🔹 9. Empty Tuple – Unit Type ()
-
()means no value -
Used when a function returns nothing
-
Similar to
voidin C/C++
🔹 10. Tuples and Ownership
✔ 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
