Rust HashMap可变借用报错:两段代码差异原因咨询
Rust HashMap Entry 可变借用冲突问题解析
可正常运行的代码
let mut results = HashMap::new(); let a = results.entry("a".to_string()).or_insert("1".to_string()); *a = "11".to_string(); let b = results.entry("b".to_string()).or_insert("2".to_string()); *b = "22".to_string();
调整顺序后编译报错的代码
let mut results = HashMap::new(); let a = results.entry("a".to_string()).or_insert("1".to_string()); let b = results.entry("b".to_string()).or_insert("2".to_string()); *a = "11".to_string(); *b = "22".to_string();
编译错误信息
cannot borrow `results` as mutable more than once at a time let a = results.entry("a".to_string()).or_insert("1".to_string()); ------------------------------ first mutable borrow occurs here let b = results.entry("b".to_string()).or_insert("2".to_string()); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here *a = "11".to_string(); -- first borrow later used here
两段代码的本质差异
核心在于Rust可变借用的生命周期范围:
- 第一段代码中,
a作为results的可变引用,其生命周期在*a = "11".to_string();执行后就结束了——这是a最后一次被使用。之后再获取b的可变引用时,results已无活跃的可变借用,符合规则。 - 第二段代码中,
a的可变引用在创建后,直到后续的*a = "11".to_string();执行完毕才会结束生命周期。此时紧接着创建b的可变引用,相当于results同时存在两个活跃的可变借用,直接违反了Rust"同一时间只能有一个可变借用"的核心规则。
你误以为a和b是独立变量,但实际上它们都是绑定到results内部元素的可变引用,这些引用的存在会限制results本身的可变借用权限。只要某个可变引用还没到最后一次使用,results就无法被其他可变借用操作。
内容的提问来源于stack exchange,提问作者Tonny Tc
相关产品推荐
相关产品推荐

