知识卡片
静态量与常量的存储
static 对应具有固定位置的存储,所保存的引用必须有静态生命周期。const 表达常量值,使用处可各自获得副本。不可变 static 可以安全读取。static mut 暴露可修改的共享存储,若几个线程访问并至少一个写入,程序必须确保相应同步,单线程示例的输出不能证明线程安全。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 高级特性 Using extern Functions to Call External Code · 查看原书依据
A subtle difference between constants and immutable static variables is that values in a static variable have a fixed address in memory. Using the value will always access the same data. Constants, on the other hand, are allowed to duplicate their data whenever they’re used. Another difference is that static variables can be mutable. Accessing and modifying mutable static variables is unsafe.
参考来源
- 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0099)
- 结论依据:原文分别解释固定地址和常量数据可重复,并说明可变静态访问属于 unsafe。
- 原始内容:A subtle difference between constants and immutable static variables is that values in a static variable have a fixed address in memory. Using the value will always access the same data. Constants, on the other hand, are allowed to duplicate their data whenever they’re used. Another difference is that static variables can be mutable. Accessing and modifying mutable static variables is unsafe.