← 返回刚才阅读的位置

知识卡片

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

构造可以是关联函数

理解等级:中级

可将创建逻辑归到类型,例如 Rectangle::square(size) 用一个尺寸初始化两条边。关联函数没有 self,通过类型路径调用。new 只是惯用名字,多种创建方式可用各自表达条件的名字。多个 impl 块也能为同一类型组织方法。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

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

      All functions defined within an impl block are called associated functions because they’re associated with the type named after the impl. We can define associated functions that don’t have self as their first parameter (and thus are not methods) because they don’t need an instance of the type to work with. We’ve already used one function like this: the String::from function that’s defined on the String type.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第05章 用结构体组织相关数据(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c05.xhtml`,块 0155) - 结论依据:原文说明 impl 内无 self 的函数可独立于实例调用。 - 原始内容:All functions defined within an impl block are called associated functions because they’re associated with the type named after the impl. We can define associated functions that don’t have self as their first parameter (and thus are not methods) because they don’t need an instance of the type to work with. We’ve already used one function like this: the String::from function that’s defined on the String type.