知识卡片
解引用转换保留借用权限
Deref 可把 &T 变成 &U,也可把 &mut T 变成 &U。若需保持可变访问,类型必须提供 DerefMut 得到 &mut U。原本共享的引用不证明独占性,不能用这种转换升级权限。
相关卡片 [[解引用转换可沿层级]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 智能指针 Implicit Deref Coercions with Functions and Methods · 查看原书依据
The third case is trickier: Rust will also coerce a mutable reference to an immutable one. But the reverse is not possible: immutable references will never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile).
参考来源
- 位置:《The Rust Programming Language(第2版)》第15章 智能指针(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c15.xhtml`,块 0146)
- 结论依据:原文从共享引用可能不唯一说明不可提升成可变借用。
- 原始内容:The third case is trickier: Rust will also coerce a mutable reference to an immutable one. But the reverse is not possible: immutable references will never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile).