struct S{data:String,
}//注意:因為String默認是移動語義,從而決定結構體S也是移動語義,可采用(1)或(2)兩種方法解決編譯錯誤;關鍵思路:放棄獲取結構體S的字段data的所有權,改為借用。fn process(s_ref:&S){//&S ,借用match *s_ref { //S , 值//(1) match s_ref { //&S , 借用//(2) S{ref data} => { //data:&String , 借用S{data} => { //出錯點.println!("Data: {}",data);},// _ => {},}
}fn main(){let s = S{data:String::from("hello world"),};process(&s);
}
編譯錯誤:
Compiling playground v0.0.1 (/playground)
error[E0507]: cannot move out of `s_ref.data` which is behind a shared reference--> src/main.rs:7:11|
7 | match *s_ref { | ^^^^^^
...
11 | S{data} => {| ----| || data moved here| move occurs because `data` has type `String`, which does not implement the `Copy` trait|
help: consider removing the dereference here|
7 - match *s_ref {
7 + match s_ref { |For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` (bin "playground") due to 1 previous error
注意:個人水平有限,難免謬誤,歡迎指正,僅做參考,拋磚引玉;怕日后遺忘,故隨筆記錄。