知识卡片
闭包按需捕获变量
闭包根据其正文需要捕获不可变引用、可变引用或所有权。打印向量只需共享借用,push 要求独占借用。捕获的借用从定义时开始,在仍要调用闭包的范围内适用通常的借用规则。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 函数式语言特性:迭代器与闭包 Capturing References or Moving Ownership · 查看原书依据
Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership. The closure will decide which of these to use based on what the body of the function does with the captured values.
参考来源
- 位置:《The Rust Programming Language(第2版)》第13章 函数式语言特性:迭代器与闭包(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c13.xhtml`,块 0043)
- 结论依据:原文将闭包捕获方式对应到借用和所有权模型。
- 原始内容:Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership. The closure will decide which of these to use based on what the body of the function does with the captured values.