← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 1395.b.1.e · 生成模型:未记录

线程闭包转移所有权

理解等级:中级

thread::spawn 可能让闭包运行到当前函数结束之后。若闭包借用了当前函数中的 Vec,调用方先释放 Vec 就会留下悬垂引用,编译器因此拒绝这种借用。move 闭包持有 Vec,线程不再依赖创建者的栈内变量,创建者也不能继续使用已移动的 Vec。若捕获的值本身是短生命周期引用,move 只移动该引用,生命周期约束仍适用。

相关卡片 [[等待线程的时机]]、[[跨线程的两种标记]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第16章 无畏并发(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c16.xhtml`,块 0061) - 结论依据:原文将默认借用导致的生命周期错误与 move 后所有权转移的版本对照。 - 原始内容:By adding the move keyword before the closure, we force the closure to take ownership of the values it’s using rather than allowing Rust to infer that it should borrow the values. The modification to Listing 16-3 shown in Listing 16-5 will compile and run as we intend.