Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Closures

Rust Closures

A closure in Rust is an anonymous function that can capture and store variables from its environment.

Closures allow accessing variables outside the defining scope, and can move or borrow them into the closure when needed.

Closures are widely used in Rust in areas such as functional programming, concurrent programming, and event-driven programming.


Differences Between Closures and Functions

Both closures and ordinary functions can encapsulate a piece of logic, but closures have one additional core capability — capturing variables from the external environment. The following table lists the main differences between the two:

Feature Closures function
Anonymity No name, usually assigned to a variable Has a fixed fn Name
Environment Capture Can capture external variables Cannot capture external variables
Definition |Parameters| Expression fn name(parameters)
Type Inference Parameter and return types can usually be omitted Parameter and return types must be explicitly specified
Storage and Passing Can be used as variables, parameters, or return values Also supported

Declaration and Invocation of Closures

The basic syntax of a closure is as follows:

let closure_name = |参数列表| 表达式或语句块;

Parameters can have type annotations or be omitted — the Rust compiler infers them from context.

Example

fn

main

(

)

{

   

// Closure: omit type annotations, the compiler infers automatically

   

let

add_one

=

|

x

|

x

1

;

    println

!

(

"add_one(4) = {}"

,

add_one

(

4

)

)

;

// Output: 5

   

// Closure: explicitly annotate parameter and return types

   

let

multiply

=

|

a

:

i32

,

b

:

i32

|

->

i32

{

a

b

}

;

    println

!

(

"multiply(3, 7) = {}"

,

multiply

(

3

,

7

)

)

;

// Output: 21

   

// Multi-line closures need curly braces

   

let

greet

=

|

name

:

&

str

|

{

       

let

greeting

=

format

!

(

"Hello, {}!"

,

name

)

;

        greeting

   

}

;

    println

!

(

"{}"

,

greet

(

"runoob"

)

)

;

// Output: Hello, runoob!

}

A closure is invoked exactly like an ordinary function: just add parentheses after the variable name and pass in arguments.


Capturing External Variables

The most core feature of a closure is the ability to capture variables in its scope. This is the essential difference between closures and ordinary functions.

Closures can capture external variables in three ways:

Capture Method Corresponding Rust Semantics Description
Capture by Reference Similar to &T Default behavior; the closure borrows the variable, and the outside can still use it
Mutable Borrow Capture Similar to &mut T The closure needs to modify the variable, and the closure itself must be declared as mut
Capture by Value Similar to T Use move keyword, moving the variable's ownership into the closure

For types that implement the Copy trait (such as i32、bool),move only a copy of the value is made and the external variable remains usable. Therefore, when demonstrating ownership transfer, you should choose String、Vec and other non- Copy type.

Capture by Reference

By default, closures borrow external variables as immutable references. After the borrow ends, the outer scope can continue to use the variable.

Example

fn

main

(

)

{

   

let

text

=

String

::

from

(

"runoob"

)

;

   

// The closure captures text by reference, without taking ownership

   

let

print_text

=

||

println

!

(

"text = {}"

,

text

)

;

    print_text

(

)

;

// Output: text = runoob

   

// The borrow has ended, and the outside can still use text

    println

!

(

"Still usable outside: {}"

,

text

)

;

}

Mutable Borrow Capture

If a closure needs to modify a captured variable, Rust captures it as a mutable reference. In this case the closure itself must be declared as mut。

Example

fn

main

(

)

{

   

let

mut

counter

=

0

;

   

// The closure captures counter with &mut, and the closure itself must also be declared mut

   

let

mut

inc

=

||

{

        counter

+=

1

;

   

}

;

    inc

(

)

;

    inc

(

)

;

    println

!

(

"counter = {}"

,

counter

)

;

// Output: counter = 2

}

Capture by Value (move)

By adding the move keyword before a closure, the closure takes ownership of the captured variables. After ownership is transferred, the outer scope can no longer use the variable.

Example

fn

main

(

)

{

   

let

owned

=

String

::

from

(

"RUNOOB"

)

;

   

// move transfers ownership of owned into the closure

   

let

take_owned

=

move

||

println

!

(

"owned = {}"

,

owned

)

;

    take_owned

(

)

;

// Output: owned = RUNOOB

   

// If you uncomment the line below, compilation will fail: ownership of owned has been moved into the closure

   

// println!("{}", owned);

}

When you need to pass a closure to another thread or return it out of the scope,move is especially commonly used — it ensures the closure holds ownership of the required data and no dangling references occur.


Closure Traits: Fn / FnMut / FnOnce

The Rust compiler automatically implements the corresponding trait for a closure based on how it captures variables. Understanding these three traits is key to using closures as function parameters or return values.

Trait Capture Method Number of Calls Typical scenario
Fn Immutable borrow (&T) Multiple times Read-only access to captured variables
FnMut Mutable borrow (&mut T) Multiple times Need to modify captured variables
FnOnce Take ownership (T) Only once Consumes captured variables and cannot be called again afterward

The inheritance relationship among the three is:Fn Is FnMut sub-trait ofFnMut Is FnOnce sub-trait of. That is to say, a closure that implements Fn automatically also implements FnMut and FnOnce。

Note:move The keyword only forces ownership to be taken; it does not mean the closure is necessarily FnOnce. If the closure body does not consume the captured values, then even with moveadded, the closure may still implement Fn(can be called multiple times).

Example

fn

main

(

)

{

   

let

name

=

String

::

from

(

"runoob"

)

;

   

// Fn closure: only reads, does not modify, can be called multiple times

   

let

greet

=

||

println

!

(

"Hello, {}!"

,

name

)

;

    greet

(

)

;

// First call

    greet

(

)

;

// Second call, still works normally

   

// FnMut closure: needs to modify captured variables

   

let

mut

count

=

0

;

   

let

mut

increment

=

||

{

        count

+=

1

;

        count

   

}

;

    println

!

(

"increment() = {}"

,

increment

(

)

)

;

// Output: 1

    println

!

(

"increment() = {}"

,

increment

(

)

)

;

// Output: 2

   

// FnOnce closure: consumes captured variables and can only be called once

   

let

data

=

String

::

from

(

"RUNOOB"

)

;

   

let

consume

=

move

||

{

       

let

_

=

data

;

// Move data out of the closure environment, consuming it

        println

!

(

"data has been consumed"

)

;

   

}

;

    consume

(

)

;

   

// consume(); // If uncommented, compilation fails: an FnOnce closure can only be called once

}


Closures as Parameters and Return Values

A closure can be passed as a function parameter or returned as a function return value. These are the two most common uses of closures in practical development.

Closures as Parameters

When passing a closure as a parameter, you need to use a generic constraint to specify the closure's trait type. In the following example, the parameter F is constrained to Fn(i32) -> i32indicating that it receives a i32 parameter and returns a i32 closure.

Example

// Define a function that accepts a closure as a parameter

fn

apply

<

F

(

val

:

i32

,

f

:

F

)

->

i32

where

    F

:

Fn

(

i32

)

->

i32

,

// F must implement Fn(i32) -> i32

{

    f

(

val

)

}

fn

main

(

)

{

   

let

double

=

|

x

|

x

2

;

   

let

result

=

apply

(

5

,

double

)

;

    println

!

(

"Result: {}"

,

result

)

;

// Output: Result: 10

   

// You can also pass an anonymous closure directly

   

let

result2

=

apply

(

3

,

|

x

|

x

100

)

;

    println

!

(

"Result2: {}"

,

result2

)

;

// Output: Result2: 103

}

Closures as Return Values

Since a closure's type is anonymous, when returning a closure you need to use impl Trait or Box to describe the return type.

Returning a Closure with impl Fn

When the returned closure type can be determined at compile time, use impl Fn which requires no heap allocation.

Example

// Return a closure that captures parameter x and adds it to the passed-in value

fn

make_adder

(

x

:

i32

)

->

impl

Fn

(

i32

)

->

i32

{

   

// move is required, otherwise x is a local reference and becomes invalid after the closure returns

    move

|

y

|

x

y

}

fn

main

(

)

{

   

let

add_five

=

make_adder

(

5

)

;

    println

!

(

"5 + 3 = {}"

,

add_five

(

3

)

)

;

// Output: 5 + 3 = 8

   

let

add_ten

=

make_adder

(

10

)

;

    println

!

(

"10 + 2 = {}"

,

add_ten

(

2

)

)

;

// Output: 10 + 2 = 12

}

Using Box to Return a Closure

When you need to dynamically choose which closure to return at runtime, use Box to allocate the closure on the heap.

Example

fn

make_adder

(

x

:

i32

)

->

Box

<

dyn Fn

(

i32

)

->

i32

{

    Box

::

new

(

move

|

y

|

x

y

)

}

fn

main

(

)

{

   

let

add_ten

=

make_adder

(

10

)

;

    println

!

(

"10 + 2 = {}"

,

add_ten

(

2

)

)

;

// Output: 10 + 2 = 12

}

Method Allocation Location Applicable scenarios
impl Fn Stack Closure type can be determined at compile time, with better performance
Box Heap Dynamically select a closure at runtime, or need to store a closure across functions

Common Application Scenarios

Closures are everywhere in daily Rust development. The following are a few of the most typical application scenarios.

Closures in Iterators

Closures are often used together with iterator methods for batch processing of collection elements.

Example

fn

main

(

)

{

   

let

nums

=

vec

!

[

1

,

2

,

3

,

4

,

5

]

;

   

// map: transform each element

   

let

squared

:

Vec

<

i32

=

nums.iter

(

)

.map

(

|

x

|

x

x

)

.collect

(

)

;

    println

!

(

"Square: {:?}"

,

squared

)

;

// Output: [1, 4, 9, 16, 25]

   

// filter: filter elements that satisfy a condition

   

let

even

:

Vec

<&

i32

=

nums.iter

(

)

.filter

(

|

x

|

x

%

2

==

0

)

.collect

(

)

;

    println

!

(

"Even: {:?}"

,

even

)

;

// Output: [2, 4]

   

// fold: reduce the collection to a single value

   

let

sum

:

i32

=

nums.iter

(

)

.fold

(

0

,

|

acc

,

x

|

acc

x

)

;

    println

!

(

"Sum: {}"

,

sum

)

;

// Output: 15

}

Closures and Multithreading

In multithreaded programming, closures are often used to define the execution body of a thread.move The keyword is almost mandatory in this scenario, because it moves ownership of the data into the new thread, avoiding cross-thread reference invalidation.

Example

use

std

::

thread

;

fn

main

(

)

{

   

let

nums

=

vec

!

[

1

,

2

,

3

,

4

,

5

]

;

   

// Create a thread for each number; move transfers ownership of num into the thread

   

let

handles

:

Vec

<

_

=

nums.into_iter

(

)

.map

(

|

num

|

{

thread

::

spawn

(

move

||

{

            num

2

       

}

)

   

}

)

.collect

(

)

;

   

// Wait for all threads to finish and collect the results

   

for

handle

in

handles

{

       

let

result

=

handle.join

(

)

.unwrap

(

)

;

        println

!

(

"Result: {}"

,

result

)

;

   

}

}

Closures and Error Handling

A closure can return the Result or Option type, working with iterator methods to implement concise error handling logic.

Example

fn

main

(

)

{

   

let

nums

=

vec

!

[

3

,

1

,

4

,

5

,

9

]

;

   

// Use a closure to find the first positive number

   

let

first_positive

=

nums.iter

(

)

.find

(

|&

amp

;&

amp

;

x

|

x

0

)

;

   

match

first_positive

{

        Some

(

&

amp

;

n

)

=>

println

!

(

"First positive number: {}"

,

n

)

,

// Output: First positive number: 3

        None

=>

println

!

(

"No positive number"

)

,

   

}

   

// Use a closure to filter and transform, with Result to handle possible errors

   

let

results

:

Vec

<

Result

<

i32

,

&

amp

;

str

=

nums.iter

(

)

.map

(

|&

amp

;

n

|

{

       

if

n

0

{

            Ok

(

n

10

)

       

}

else

{

            Err

(

"Negative numbers cannot be processed"

)

       

}

   

}

)

.collect

(

)

;

   

for

r

in

results

{

       

match

r

{

            Ok

(

v

)

=>

println

!

(

"Success: {}"

,

v

)

,

            Err

(

e

)

=>

println

!

(

"Error: {}"

,

e

)

,

       

}

   

}

}


Performance and Lifetimes

Closure Performance

Rust's closures are lightweight. The compiler performs inlining optimizations on closures, making the overhead of a closure call close to that of a direct call to an ordinary function. Closures themselves introduce no extra virtual function calls or heap allocations (unless explicitly using Box)。

Closures and Lifetimes

A closure's lifetime is closely related to the variables it captures. Rust's lifetime system ensures that a closure does not outlive any variable it captures — if a closure references a local variable, the compiler will prevent you at compile time from returning the closure outside that variable's scope.

Example

fn

main

(

)

{

   

let

text

=

String

::

from

(

"runoob"

)

;

   

// Correct: the closure is used within text's scope

   

let

print_text

=

||

println

!

(

"{}"

,

text

)

;

    print_text

(

)

;

// Output: runoob

   

// If you try to return this closure, the compiler will report an error:

   

// fn make_closure() -> impl Fn() {

   

//     let text = String::from("runoob");

   

// || println!("{}", text) // Error: text does not live long enough

   

// }

   

// Solution: use move to transfer ownership into the closure

}


Complete example

The following example comprehensively demonstrates core usages of closures such as declaration, capturing external variables, and passing as parameters.

Example

// Define a function that accepts a closure as a parameter

fn

apply_operation

<

F

(

num

:

i32

,

operation

:

F

)

->

i32

where

    F

:

Fn

(

i32

)

->

i32

,

{

    operation

(

num

)

}

fn

main

(

)

{

   

let

num

=

5

;

   

// Define a closure that squares a number

   

let

square

=

|

x

|

x

x

;

   

// Pass the closure as a parameter to a function

   

let

result

=

apply_operation

(

num

,

square

)

;

    println

!

(

"Square of {} is {}"

,

num

,

result

)

;

// Output: Square of 5 is 25

   

// You can also pass an anonymous closure directly

   

let

result2

=

apply_operation

(

num

,

|

x

|

x

x

x

)

;

    println

!

(

"Cube of {} is {}"

,

num

,

result2

)

;

// Output: Cube of 5 is 125

}

Running this program, the output is as follows:

Square of 5 is 25

Cube of 5 is 125


Summary

Rust's closures are a powerful abstraction, providing a flexible and expressive way to encapsulate logic.

Closures can capture environmental variables and can be passed as parameters or returned as return values. When combined with iterators, closures can conveniently implement complex data processing tasks.

Rust's closure design balances safety, performance, and lifetimes — the compiler ensures at compile time that closures do not reference invalidated variables, and through inlining optimization guarantees zero-cost abstraction for closure calls.