知识卡片

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

接收者表达访问权限

理解等级:中级

方法的接收者决定调用者交出的权限。&self 表示共享读取,&mut self 表示独占访问,self 表示按值传入,可用来把原对象转换为另一个值。点调用可自动调整接收者,但其权限仍以方法签名为准。

相关卡片 [[可变借用要求独占]]、[[借用以引用传递访问]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 用结构体组织相关数据 Method Syntax · 查看原书依据

      We chose &self here for the same reason we used &Rectangle in the function version: we don’t want to take ownership, and we just want to read the data in the struct, not write to it. If we wanted to change the instance that we’ve called the method on as part of what the method does, we’d use &mut self as the first parameter.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第05章 用结构体组织相关数据(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c05.xhtml`,块 0129) - 结论依据:原文用 area 示例区分 &self、&mut self 与按值 self。 - 原始内容:We chose &self here for the same reason we used &Rectangle in the function version: we don’t want to take ownership, and we just want to read the data in the struct, not write to it. If we wanted to change the instance that we’ve called the method on as part of what the method does, we’d use &mut self as the first parameter.