Borrowed in rust 1.60.0

Hello everyone, i am newbie . I have a question about borrowed in rust
struct Blog {

year: i32,

name: &'static str,

}

fn main() {

let mut code: Blog = Blog {

    year: 2021,

    name: "code",

};

let code2 = &mut code;

code2.name = "Henry";

println!("{}",code2.name);

code.year = 2022; // Why code value not prevent

}// Still working OK but

struct Blog {

year: i32,

name: &'static str,

}

fn main() {

let mut code: Blog = Blog {

    year: 2021,

    name: "code",

};

let code2 = &mut code;

code2.name = "Henry";
code.year = 2022; //cannot assign to `code.year` because it is borrowed
                               //assignment to borrowed `code.year` occurs here
println!("{}",code2.name);

}//Error

Can you please explain to me?

In the first example code2 is not used after the println!, so the borrow can be considered released, thus you're able to use code again. In the second example however code2 is used after code, meaning when you use code the borrow of code2 is still alive and the use of code is invalid.

1 Like

When I run ex1 on "Online Rust Compiler" , the compile error message appears. Is there a logical difference between the versions?

Rust 1.19 is fairly old - in particular, it's older then the 2018 edition, where the current behavior was estabilished. Compiler used to be more restrictive, rejecting some valid programs because it couldn't prove they're valid. In particular, it couldn't see that it can end the borrow early - they all ended at the end of scope (i.e. on the closing curly brace). So, yes, for the old version there is a logical difference, but for current versions there's none.

By the way, if you need the online compiler for Rust, consider either playground or godbolt - they are hosting up-to-date compilers and can help you avoid such problems with older toolchains.

7 Likes

Thank you so much, I got the answer for me

you may have stumbled into Non-Lexical Lifetimes:

1 Like