The || syntax in Rust - also known as a closure

CK CK 3788 
Created at  
602 0 0

The || syntax in Rust represents the definition of a closure. A closure is a function-like construct that you can define inline and pass around. It allows you to encapsulate a block of code with optional input parameters and a return value.

In the context of the provided code:

let handle1 = thread::spawn(|| {
    for i in 1..5 {
        println!("Thread 1 - Count: {}", i);
        thread::sleep(Duration::from_millis(500)); // Simulate work
    }
});

Key Points about ||:

  1. Parameter Declaration:

    • The || part defines the input parameters for the closure.
    • In this case, the closure has no parameters (hence the empty ||).

    Example with parameters:

    let closure = |x: i32| x * 2; // A closure that takes one integer and doubles it.
    println!("{}", closure(5)); // Outputs 10
    
  2. Body of the Closure:
    • The block { ... } contains the code that the closure will execute.
  3. Anonymous Nature:
    • Closures are anonymous functions, meaning they don't have a name and are typically used in situations where you need a short-lived function.

In the Thread Example

  • The closure || { ... } is passed to thread::spawn, which runs the closure in a new thread.
  • The closure has no parameters (|| is empty) and performs a task in the thread.

Why Use Closures?

Closures are lightweight, can capture variables from their surrounding environment, and are convenient for tasks like:

  • Passing functions to another function (e.g., thread::spawn).
  • Inline short-lived computations.

For example, closures can "capture" variables from the enclosing scope:

let x = 10;
let closure = || println!("Value of x: {}", x);
closure(); // Prints: Value of x: 10

This ability to capture variables makes closures very flexible compared to standard functions.

Tags Closure Rust Closure spawn thread Facebook X
Comments 0
Similar posts
  1. Basic Rust Thread Example to Perform Concurrent Computation
    618
  2. Multi-threaded HLS Server in Rust
    774
  3. Rust Std library types
    370
  4. Rust Thread Example
    346
  5. How do I get the maximum available of thread in python?
    995
  6. Method to maximize full CPU performance with Python
    325
  7. Thread Application Implementation in TThread
    670
  8. Calling Your Main Thread From A Worker Thread In C#
    551
  1. How do I implement a heap in Rust?
    685
  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)
    624
  6. Run a specific module in a external file with Rust
    571
  7. Question(?) Operator in Rust
    573
  8. Rust code example to access MySQL
    1,100
  9. Rust Documentation
    316
  10. Rust Compatibility
    726
  11. Rust Unsafe Operations
    369
  12. Rust Testing
    1,246
  13. Rust Std misc
    375
  14. Rust Error Handling
    350
  15. Rust Macro Rules
    1,525
  16. Rust mechanism for defining shared behavior across different types - Traits
    1,774
  17. Rust Scoping Rules - only accessible within the block of code
    1,075
  18. Rust Generics - Generalizing types and functionalities
    1,358
  19. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    318
  20. Rust Package Management Tool - cargo
    307
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,255
  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
    104
  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
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  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
    598
  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
    230
  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
    263
  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