Tuples in Rust - a collection of values of different types

CK CK 3788 
Created at
Updated at  
298 0 0

In Rust, tuples are immutable, fixed-size collections of values of potentially different types, accessed by their index. Python tuples are also immutable, fixed-size sequences, but offer more flexible indexing and iteration methods. C++ doesn't have a direct equivalent; tuples are often simulated using std::pair (for two elements) or std::tuple (for more), but these lack Python's inherent tuple-like syntax and can be mutable depending on the types within. Key differences lie in mutability (Rust and Python tuples are immutable, C++'s are not necessarily so), syntax and ease of use (Python's are the most concise), and the presence of built-in tuple support (Rust and Python have direct language support, C++ uses standard library constructs).

In Rust, a tuple is a collection of values of different types. Tuples are constructed using parentheses (), and each tuple itself is a value with type signature (T1, T2, ...), where T1, T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values.

// Tuples can be used as function arguments and as return values.
fn reverse(pair: (i32, bool)) -> (bool, i32) {
    // `let` can be used to bind the members of a tuple to variables.
    let (int_param, bool_param) = pair;

    (bool_param, int_param)
}

// The following struct is for the activity.
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);

fn main() {
    // A tuple with a bunch of different types.
    let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);

    // Values can be extracted from the tuple using tuple indexing.
    println!("Long tuple first value: {}", long_tuple.0);
    println!("Long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members.
    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

    // Tuples are printable.
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    // But long Tuples (more than 12 elements) cannot be printed.
    //let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    //println!("Too long tuple: {:?}", too_long_tuple);
    // TODO ^ Uncomment the above 2 lines to see the compiler error

    let pair = (1, true);
    println!("Pair is {:?}", pair);

    println!("The reversed pair is {:?}", reverse(pair));

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses.
    println!("One element tuple: {:?}", (5u32,));
    println!("Just an integer: {:?}", (5u32));

    // Tuples can be destructured to create bindings.
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("{:?}", matrix);
}

 

Tags Rust Data Types Rust Tuples Tuples Facebook X
Comments 0
Similar posts
  1. Arrays and Slices in Rust
    341
  2. Literals and operators in Rust
    299
  3. Rust Custom Data Types - struct, enum, use, constants
    299
  4. Rust Data Type - What is mutable?
    256
  5. Rust Data Type Operations - Casting, Literals, Inference, Aliasing
    326
  1. Rust Error Handling
    349
  2. Rust Macro Rules
    1,521
  3. Rust mechanism for defining shared behavior across different types - Traits
    1,771
  4. Rust Scoping Rules - only accessible within the block of code
    1,073
  5. Rust Generics - Generalizing types and functionalities
    1,356
  6. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    317
  7. Rust Package Management Tool - cargo
    307
  8. Rust compilation unit - Crates
    254
  9. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,908
  10. Rust functions - Methods, Closures, Capturing
    1,208
  11. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    339
  12. Rust Expressions
    933
  13. Rust Conversion - From, Into, TryFrom, TryInto
    1,320
  14. gRPC library for Rust
    345
  15. Variable Bindings in Rust
    975
  16. Rust Code Testing Environment without installing anything on your computer
    326
  17. Rust Thread Example
    346
  18. How do I setup Rust development environment?
    369
  19. Rust - System Programming Language invented by Graydon Hoare
    280
  20. Why America's Biggest Tech Companies Are Betting on Rust?
    290
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    28
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,829
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    228
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232