Question(?) Operator in Rust

CK CK 3788 
Created at  
574 0 0

The ? operator in Rust is a concise way to propagate errors. It simplifies error handling by either:

  1. Returning the Ok value if the result is successful.
  2. Returning the Err value if an error occurs, propagating it to the caller.

How It Works

When you apply the ? operator to a Result or Option:

  • If the value is Ok(v), it extracts v and continues execution.
  • If the value is Err(e), it returns Err(e) from the current function.

Example with Result

fn read_file(path: &str) -> std::io::Result<String> {
    let content = std::fs::read_to_string(path)?; // If an error occurs, it propagates up
    Ok(content) // Otherwise, returns the file content
}

fn main() {
    match read_file("example.txt") {
        Ok(content) => println!("File content: {}", content),
        Err(err) => eprintln!("Error reading file: {}", err),
    }
}

Example with Option

fn get_first_char(s: &str) -> Option<char> {
    let first_char = s.chars().next()?; // Propagates `None` if `next()` returns `None`
    Some(first_char)
}

fn main() {
    let text = "hello";
    match get_first_char(text) {
        Some(c) => println!("First character: {}", c),
        None => println!("String is empty"),
    }
}

Requirements

  • The function using ? must return a Result or Option (or another compatible type).
  • If the function returns something else, you’ll need to convert the error type explicitly.

Why Use ?

  • Readable: Reduces boilerplate compared to match statements.
  • Efficient: Automatically handles early returns for errors.

In short, ? is a shorthand for handling Result and Option values elegantly, making Rust's error-handling mechanism both safe and convenient.

Tags Question Operator Rust Operators Facebook X
Comments 0
Similar posts
  1. Literals and operators in Rust
    300
  1. How do I implement a heap in Rust?
    686
  2. How do I implement a stack in Rust?
    771
  3. Rust-GPU-tools for interacting with various GPU APIs
    757
  4. Rust array is fixed size. Can I modify its content?
    587
  5. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    625
  6. The || syntax in Rust - also known as a closure
    602
  7. Basic Rust Thread Example to Perform Concurrent Computation
    619
  8. Multi-threaded HLS Server in Rust
    774
  9. Run a specific module in a external file with Rust
    571
  10. Rust code example to access MySQL
    1,100
  11. Rust Documentation
    316
  12. Rust Compatibility
    726
  13. Rust Unsafe Operations
    369
  14. Rust Testing
    1,246
  15. Rust Std misc
    375
  16. Rust Std library types
    370
  17. Rust Error Handling
    350
  18. Rust Macro Rules
    1,525
  19. Rust mechanism for defining shared behavior across different types - Traits
    1,774
  20. Rust Scoping Rules - only accessible within the block of code
    1,075
  21. Rust Generics - Generalizing types and functionalities
    1,358
  22. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    318
  23. Rust Package Management Tool - cargo
    307
  24. Rust compilation unit - Crates
    254
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    304
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    232
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  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
    264
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233