Rust入坑指南:核心概念 之测试,因该文中涉及一些代码不知道是什么效果,所以就做了如下的测试:

Ownership的移动 — 在String之间转移

  1. let s1 = String::from("hello");
  2. let s2 = s1;
  3. println!("s1: {}", s1);

执行上面的代码会报如下错误:

  1. warning: unused variable: `s2`
  2. --> src\main.rs:7:7
  3. |
  4. 7 | let s2 = s1;
  5. | ^^ help: if this is intentional, prefix it with an underscore: `_s2`
  6. |
  7. = note: `#[warn(unused_variables)]` on by default
  8. error[E0382]: borrow of moved value: `s1`
  9. --> src\main.rs:8:22
  10. |
  11. 6 | let s1 = String::from("hello");
  12. | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
  13. 7 | let s2 = s1;
  14. | -- value moved here
  15. 8 | println!("s1: {}", s1);
  16. | ^^ value borrowed here after move
  17. error: aborting due to previous error; 1 warning emitted
  18. For more information about this error, try `rustc --explain E0382`.
  19. error: could not compile `hello_cargo`
  20. To learn more, run the command again with --verbose.