error[E0382]: use of moved value: `s1` --> src/main.rs:5:28 | 3 | let s2 = s1; | -- value moved here 4 | 5 | println!("{}, world!", s1); | ^^ value used here after move | = note: move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait
函数传值转移
1 2 3 4 5 6 7 8 9 10
fnmain() { let s = String::from("hello"); // s 进入作用域 takes_ownership(s); // s 的值移动到函数里 ... // ... 所以到这里不再有效 println!("{}", s); }
| 2 | let s = String::from("hello"); // s 进入作用域 | - move occurs because `s` has type `String`, which does not implement the `Copy` trait 3 | takes_ownership(s); // s 的值移动到函数里 ... | - value moved here 4 | // ... 所以到这里不再有效 5 | println!("{}", s); | ^ value borrowed here after move | = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
引用
由于默认的所有权转移存在,当我们仅需要只读变量,并不想将所有权转移时,就需要引用。
语法:&s
1 2 3 4 5 6 7 8 9 10
fnmain() { let s = String::from("hello"); // s 进入作用域 takes_ownership(&s); // &s表示在takes_ownership中只读,并不会修改他的值 // 所以到这里不再有效 println!("{}", s); }