《Programming Rust》共享引用疑问:可达节点为何标记not read-only?
关于Rust共享引用与嵌套数据结构的疑问解析
《Programming Rust》中的共享引用定义
Shared access is read-only access. Values borrowed by shared references are read-only. Across the lifetime of a shared reference, neither its referent, nor anything reachable from that referent, can be changed by anything. There exist no live mutable references to anything in that structure, its owner is held read-only, and so on. It’s really frozen.
参考配图

核心疑问
定义中明确提到nor anything reachable from that referent(引用指向的对象及其可访问到的所有内容都应处于只读状态),但图中标记为not read-only的两个节点明明可以从引用对象访问到,却未被标记为只读,这与定义产生矛盾,为何会出现这种情况?
问题解析
这是对Rust共享引用“只读范围”的常见误解,核心点在于:共享引用的只读限制针对的是“通过该引用的访问路径”,而非所有可达节点本身。
- 当持有共享引用
&A时,Rust会冻结所有通过&A能直接或间接访问到的数据的修改路径——你无法通过&A修改A的任何字段,包括其中的&mut B指针本身(比如不能将该指针指向其他B实例)。 - 图中
not read-only的B和C实例,它们的可变性来源于独立存在的&mut B可变引用。这个可变引用的生命周期与&A共享引用相互独立,只要它的存在符合Rust的借用规则(比如未与&A产生冲突的借用),就可以通过该可变引用直接修改B和C。 - 回到定义的表述:“neither its referent, nor anything reachable from that referent, can be changed by anything”中的“anything reachable”,实际指的是通过该共享引用能够访问并修改的内容。你无法通过
&A这条路径修改B和C,这完全符合定义要求——这里的“不能被任何方式修改”,限定的是通过该共享引用的修改路径,而非所有可能的修改路径。
内容的提问来源于stack exchange,提问作者Srikar
相关产品推荐
相关产品推荐

