Compiling ownership v0.1.0 (/home/xiyuanyang/Rust/ownership) error[E0382]: borrow of moved value: `s1` --> src/main.rs:21:20 | 13 | let s1 = String::from("Hello world"); | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait ... 17 | let s2 = s1; | -- value moved here ... 21 | println!("{}", s1); | ^^ value borrowed here after move | = note: this error originates inthe macro `$crate::format_args_nl` which comes fromthe expansion ofthe macro `println` (in Nightly builds, runwith -Z macro-backtrace for more info) help: consider cloning the value ifthe performance cost is acceptable | 17 | let s2 = s1.clone(); | ++++++++
For more information about this error, try `rustc --explain E0382`. error: could not compile `ownership` (bin "ownership") due to1 previous error
为了理解这个编译错误,我们需要理解程序在内存上都干了什么:
对于一个String类的变量,程序会在内存中储存三个信息:ptr, length and capacity,这三个信息本身储存在栈内存中。而指针所指向的具体的内存(就是实际的data)是分配在堆内存中的,在进行赋值操作的时候,程序会将指针,长度和capacity这三个变量的值都拷贝一份给新的变量s2,但是不会开辟一块新的内存给s2使用!(这就是严重的对指针变量的浅拷贝)
/* * @Author: Xiyuan Yang xiyuan_yang@outlook.com * @Date: 2025-04-16 19:57:16 * @LastEditors: Xiyuan Yang xiyuan_yang@outlook.com * @LastEditTime: 2025-04-19 01:19:36 * @FilePath: /Rust/ownership/src/main.rs * @Description: * Do you code and make progress today? * Copyright (c) 2025 by Xiyuan Yang, All Rights Reserved. */
fncauculate_length(s: &mutString) ->usize { s.push_str("I am a boy"); s.len() }
报错:
1 2 3 4 5 6 7 8 9 10 11 12 13
error[E0499]: cannot borrow `s3` as mutable more than once at a time --> src/main.rs:22:14 | 21 | let s4 = & mut s3; | -------- first mutable borrow occurs here 22 | let s5 = & mut s3; | ^^^^^^^^ second mutable borrow occurs here 23 | 24 | println!("{}{}", s4, s5); | -- first borrow later used here
For more information about this error, try `rustc --explain E0499`. error: could not compile `Borrow` (bin "Borrow") due to1 previous error
Compiling Borrow v0.1.0 (/home/xiyuanyang/Rust/Borrow) error[E0106]: missing lifetime specifier --> src/main.rs:17:16 | 17 | fn dangle() -> &String{ | ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static` | 17 | fn dangle() -> &'staticString{ | +++++++ help: instead, you are more likely to want toreturn an owned value | 17 - fn dangle() -> &String{ 17 + fn dangle() ->String{ |
error[E0515]: cannot return reference to local variable `s` --> src/main.rs:19:5 | 19 | &s | ^^ returns a reference to data owned by the current function
Some errors have detailed explanations: E0106, E0515. For more information about an error, try `rustc --explain E0106`. error: could not compile `Borrow` (bin "Borrow") due to2 previous errors