乐闻世界logo
搜索文章和话题

What are the types of closure capture in Rust?

1个答案

1

In Rust, closures have three main types of captures:

  1. By Value - Using the move keyword: When a closure captures a variable by value, it takes ownership of the variable. This means that once captured, the original variable is no longer accessible because ownership has been transferred to the closure. This capture method is commonly used when you want to keep a copy of the variable inside the closure or when you need to modify the variable within the closure without affecting the external variable.
rust
let x = 10; let c = move || println!("captured by value: {}", x); c(); // x is no longer accessible, as ownership has been moved to closure c
  1. By Mutable Reference: A closure can capture a variable by mutable reference, allowing it to modify variables in the external environment. To achieve this, you need to add the move keyword before the closure and ensure the variable is mutable.
rust
let mut x = 10; let mut c = || { x += 1; println!("captured by mutable reference: {}", x); }; c(); println!("x after modification: {}", x);
  1. By Immutable Reference: This is the most common capture method for closures. A closure captures a variable by immutable reference, allowing it to access and use the value of the external variable but not modify it.
rust
let x = 10; let c = || println!("captured by immutable reference: {}", x); c(); println!("x is still accessible here: {}", x);

These three capture methods provide flexibility for Rust closures to handle various scenarios. Selecting the right capture method depends on your specific requirements, such as whether you need to modify variables or whether you want the closure to take ownership of the variable.

2024年8月7日 14:39 回复

你的答案