知识卡片
Deref 返回目标借用
自定义包装类型可以实现 Deref,声明关联类型 Target 并实现 deref(&self) -> &Self::Target。对 MyBox<T>(T),返回 &self.0,编译器可把 *y 解释为先取这个借用,再普通解引用。访问内部值时要遵守借用规则。
相关卡片 [[智能指针组合管理行为]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 智能指针 Treating Smart Pointers Like Regular References with Deref · 查看原书依据
The reason the deref method returns a reference to a value, and that the plain dereference outside the parentheses in *(y.deref()) is still necessary, has to do with the ownership system. If the deref method returned the value directly instead of a reference to the value, the value would be moved out of self.
参考来源
- 位置:《The Rust Programming Language(第2版)》第15章 智能指针(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c15.xhtml`,块 0119)
- 结论依据:原文用返回值会导致移出来解释为何 deref 方法返回引用。
- 原始内容:The reason the deref method returns a reference to a value, and that the plain dereference outside the parentheses in *(y.deref()) is still necessary, has to do with the ownership system. If the deref method returned the value directly instead of a reference to the value, the value would be moved out of self.