sunface / rust-course

“连续八年成为全世界最受喜爱的语言,无 GC 也无需手动内存管理、极高的性能和安全性、过程/OO/函数式编程、优秀的包管理、JS 未来基石" — 工作之余的第二语言来试试 Rust 吧。本书拥有全面且深入的讲解、生动贴切的示例、德芙般丝滑的内容,这可能是目前最用心的 Rust 中文学习教程 / Book
https://course.rs
25.21k stars 2.18k forks source link

学习引用与借用的时候,有一点搞不明白 #1352

Closed gitscofield closed 9 months ago

gitscofield commented 9 months ago

在学习引用与借用的时候,我有一点搞不明白: fn main() { let mut s = String::from("hello, "); let r1 = &mut s; println!("{}",s); // 为什么这里打印s可以 let r2 = &mut s; println!("{}",s); // 为什么这里打印s报错 println!("{}", r2); // 这里打印r2不报错 }

Compiling playground v0.0.1 (/playground) warning: unused variable: r1 --> src/main.rs:14:9 14 let r1 = &mut s; ^^ help: if this is intentional, prefix it with an underscore: _r1

= note: #[warn(unused_variables)] on by default

error[E0502]: cannot borrow s as immutable because it is also borrowed as mutable --> src/main.rs:17:19 16 let r2 = &mut s; ------ mutable borrow occurs here 17 println!("{}",s); ^ immutable borrow occurs here 18 19 println!("{} ", r2); -- 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)

For more information about this error, try rustc --explain E0502. warning: playground (bin "playground") generated 1 warning error: could not compile playground (bin "playground") due to previous error; 1 warning emitted 🌟🌟