知识卡片

延伸参考卡 · 6074.d.1.a.3.c.1.a.3 · 生成模型:GPT-6

首次解引用触发初始化

理解等级:中级

书中 lazy_static! 将声明生成一个包装类型和同名静态实例。包装类型的 Deref 将初始化表达式交给一次性存储,第一次访问才算出值,后续解引用复用该值。初始化从编译期挪到运行时,适合初始化贵或依赖运行时能力且可能始终不用的值。书中的源码为简化版本,依赖后端要按具体配置判断。

相关卡片 [[宏和依赖各有作用域]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Declarative macros lazy_static 源码示例 · 查看原书依据

      The second arm (@TAIL) creates a Deref and initialization. This is where the magic happens. If you need your lazily initialized static somewhere in your code, you will dereference it as soon as you start using it. It is at that point that the initialization expression that you provided will run.

    参考来源

    - 位置:《Write Powerful Rust Macros》第02章《Declarative macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-2.xhtml#p158) - 结论依据:书中 @MAKE TY 生成包装器,@TAIL 生成解引用,再由 Lazy::get 安排一次性初始化。 - 原始内容:The second arm (@TAIL) creates a Deref and initialization. This is where the magic happens. If you need your lazily initialized static somewhere in your code, you will dereference it as soon as you start using it. It is at that point that the initialization expression that you provided will run.