Argomenti importanti di Rust
Rust Closures
Functions without a name that remember the variables around them.
Cosa imparerai
- |n| n * 2
- Capturing variables
- move and returning closures
Closure → result
|n| n * 2apply(21) → 42|n| n + bonusapply(5) → 15make_adder(5)add_five(1) → 6A function that captures its surroundings
A closure is a function without a name that you can store in a variable or pass to another function. Unlike a normal function, it can use variables from the place where it was created.
|n| n * 2 is a closure with one parameter. add_bonus reads bonus from the surrounding code. move makes the closure own what it captures, which is needed when the closure is returned from make_adder. increment changes counter, so it must be declared mut.
Punti chiave
- A closure can use variables from where it was created.
- move makes it own what it captures.
- A closure that changes a variable must be mut.
Esempio Rust eseguibile
main.rs
fn apply(value: i32, operation: impl Fn(i32) -> i32) -> i32 {
operation(value)
}
fn make_adder(amount: i32) -> impl Fn(i32) -> i32 {
move |value| value + amount
}
fn main() {
let double = |n| n * 2;
println!("{}", apply(21, double));
let bonus = 10;
let add_bonus = |n| n + bonus; // captures bonus from the environment
println!("{}", apply(5, add_bonus));
let add_five = make_adder(5);
println!("{}", add_five(1));
let mut counter = 0;
let mut increment = || counter += 1;
increment();
increment();
println!("counter = {counter}");
}
42
15
6
counter = 2Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
Tutte le sfide