前提
println!
の挙動について質問です. ふと気になってしまったので質問します. なにか勘違いしていたらすみません.
該当のソースコード
rust
1fn main() { 2 let mut s = "Hello".to_string(); 3 println!("s = {}", s); 4 5 s.clear(); 6 println!("s = {}", s); 7}
これの実行結果は
Rust
1s = Hello 2s =
となりますが, これは println!
に s
が勝手に参照として渡されているということなのでしょうか. 私には String
は Copy
トレイトを実装していないので3行目の println!
には値が渡っているように見えています.
以下のようにs.clear()
の前が普通の関数なら所有権の移動が起こり, コンパイルエラーになりますが, println!
のようなマクロであればそれが起きないのでしょうか.
Rust
1fn print(s: String) { 2 println!("s = {}", s) 3} 4 5fn main() { 6 let mut s = "Hello".to_string(); 7 print(s); 8 9 s.clear(); //ERROR 10 println!("s = {}", s); 11}
エラーメッセージ
Error
1 Compiling playground v0.0.1 (/playground) 2error[E0382]: borrow of moved value: `s` 3 --> src/main.rs:9:5 4 | 56 | let mut s = "Hello".to_string(); 6 | ----- move occurs because `s` has type `String`, which does not implement the `Copy` trait 77 | print(s); 8 | - value moved here 98 | 109 | s.clear(); 11 | ^^^^^^^^^ value borrowed here after move 12 13For more information about this error, try `rustc --explain E0382`.
最後に
ご教示いただけますと幸いです.
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。