← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.e.8 · 生成模型:未记录

解引用转换可沿层级

理解等级:中级

当调用签名需要另一种引用时,编译器可沿 Deref 链插入转换,例如 &MyBox<String> → &String → &str。这些转换保持借用关系,无需在调用处逐级手写取引用与解引用。

相关卡片 [[Deref 返回目标借用]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 智能指针 Implicit Deref Coercions with Functions and Methods · 查看原书依据

      Here we’re calling the hello function with the argument &m, which is a reference to a MyBox<String> value. Because we implemented the Deref trait on MyBox<T> in Listing 15-10, Rust can turn &MyBox<String> into &String by calling deref. The standard library provides an implementation of Deref on String that returns a string slice, and this is in the API documentation for Deref.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第15章 智能指针(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c15.xhtml`,块 0132) - 结论依据:两次 trait 调用把 `&MyBox<String>` 变为参数需要的 `&str`。 - 原始内容:Here we’re calling the hello function with the argument &m, which is a reference to a MyBox<String> value. Because we implemented the Deref trait on MyBox<T> in Listing 15-10, Rust can turn &MyBox<String> into &String by calling deref. The standard library provides an implementation of Deref on String that returns a string slice, and this is in the API documentation for Deref.