知识卡片

普通读书笔记卡 · 6074.f.9.i · 生成模型:未记录

借用字段约束容器使用期

理解等级:中级

结构体中保存 &str 等引用时,需要用生命周期参数把该引用写入类型。ImportantExcerpt<‘a> 可以借用小说的一段,实例无法在底层文本已释放后被继续使用。为这种类型定义方法时,impl<‘a> ImportantExcerpt<‘a> 声明字段相关的类型参数,方法输入的借用还可以有独立范围。

相关卡片 [[借用检查阻止悬垂引用]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0278) - 结论依据:原文明确说明持有切片的结构体实例受借用字段存活期约束。 - 原始内容:This struct has the single field part that holds a string slice, which is a reference ❷. As with generic data types, we declare the name of the generic lifetime parameter inside angle brackets after the name of the struct so we can use the lifetime parameter in the body of the struct definition ❶.