rust的生命周期问题理解(一)

复制代码
fn main() {
    let mut a = String::new();
    let mut b = &mut a;
    println!("{:?}",a);
    b.push('a');
}
复制代码
error[E0502]: cannot borrow `a` as immutable because it is also borrowed as mutable
  --> src/main.rs:9:21
   |
8  |     let mut b = &mut a;
   |                 ------ mutable borrow occurs here
9  |     println!("{:?}",a);
   |                     ^ immutable borrow occurs here
10 |     b.push('a');
   |     - mutable borrow later used here
   |
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

原因是a和b变量都指向同一个内存区域

a和b都对应同一个区域有write的权限。

println!("{:?}",a);这句话将对a进行不可变的借用

问题出在了10行。此行b是对a的一个可变借用。

第9行是对a的不可变借用,第10行是对a的可变借用。两者矛盾。编译报错。

同理是:

复制代码
fn main() {

    //
    let rc = Rc::new(vec![1, 2, 3]);

    // 创建一个共享引用
    let  mut rc_clone = Rc::clone(&rc);

    // 此时的引用计数为2,`make_mut` 会在需要修改时进行克隆
    // let mut binding = rc.clone();
    let rc_mut = Rc::make_mut(&mut rc_clone);

    // 现在可以安全地修改 `rc_mut`,原始的 `rc` 和 `rc_clone` 不受影响
    rc_mut.push(4);
    // println!("rc length: {:?}", Rc::strong_count(&rc));
    println!("rc: {:?}", rc);           // [1, 2, 3]
    println!("rc_clone: {:?}", rc_clone); // [1, 2, 3]
    // println!("rc_mut: {:?}", rc_mut);    // [1, 2, 3, 4]
    rc_mut.push(4);
}

rc_mut是对rc_clone的可变借用。

println!("rc_clone: {:?}", rc_clone);变成了对rc_clone的不可变借用

两者矛盾了。因此报错。

但是这里面Rc::make_mut(&mut rc_clone);调用结束了后,为什么还认为存在对rc_clone的可变借用呢?原因见chatgpt回答:

一个更简单的类似的例子是这个:

复制代码
fn test(b :& String) {
    println!("{:?}",b)
}

fn test2(b :&mut String) -> &mut String{
    b.push('b');
    println!("{:?}",b);
    return b;
}

fn main() {
    let mut a = String::new();
    let c = test2(&mut a);
    test(&a);
    a.push('a');
    c.push('b');
}

cannot borrow a as immutable because it is also borrowed as mutable 是什么错误,详细解释下

相关推荐
自由随风飘8 小时前
python 题目练习1~5
开发语言·python
Bony-9 小时前
Go语言完全学习指南 - 从基础到精通------语言基础篇
服务器·开发语言·golang
天若有情6739 小时前
【java EE】IDEA 中创建或迁移 Spring 或 Java EE 项目的核心步骤和注意事项
后端·spring·java-ee·intellij-idea
fl17683110 小时前
基于python的天气预报系统设计和可视化数据分析源码+报告
开发语言·python·数据分析
ACP广源盛1392462567310 小时前
(ACP广源盛)GSV6172---MIPI/LVDS 信号转换为 Type-C/DisplayPort 1.4/HDMI 2.0 并集成嵌入式 MCU
c语言·开发语言·单片机·嵌入式硬件·音视频
不穿格子的程序员10 小时前
从零开始刷算法-栈-括号匹配
java·开发语言·
雪域迷影11 小时前
C#中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·http·c#·get
yue00811 小时前
C#类继承
java·开发语言·c#
Want59511 小时前
Python汤姆猫
开发语言·python
大鱼七成饱11 小时前
💥 从崩溃到稳定:我踩过的 Rust Tokio 线程池坑(含代码示例)
后端