![](/img/trans.png)
[英]What is the best way to reuse a borrowed struct field if it doesn't implement the Copy or Clone trait?
[英]Can I reuse a struct field during type conversion without calling .clone()?
我目前有兩個相似的結構,我需要實現From
特性以將一個轉換為另一個。 但是,我收到一條錯誤消息:
error[E0382]: borrow of moved value: `item.my_first_string`
--> src/lib.rs:14:30
|
13 | my_second_string: item.my_first_string,
| -------------------- value moved here
14 | string_is_empty: item.my_first_string.is_empty(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
= note: move occurs because `item.my_first_string` has type `String`, which does not implement the `Copy` trait
這是我的代碼的樣子:
struct Foo {
my_first_string: String,
}
struct Bar {
my_second_string: String,
string_is_empty: bool,
}
impl From<Foo> for Bar {
fn from(item: Foo) -> Self {
Bar {
my_second_string: item.my_first_string,
string_is_empty: item.my_first_string.is_empty(),
}
}
}
我知道我可以在my_first_string
上調用.clone
來滿足借用檢查器的要求,但這似乎是不必要的。 有沒有辦法在沒有.clone()
的情況下使用這個字段兩次?
在移動字符串之前,只需將is_empty()
的結果存儲為一個變量:
impl From<Foo> for Bar {
fn from(item: Foo) -> Self {
let string_is_empty = item.my_first_string.is_empty();
Bar {
my_second_string: item.my_first_string,
string_is_empty,
}
}
}
或者只是顛倒順序:
impl From<Foo> for Bar {
fn from(item: Foo) -> Self {
Bar {
string_is_empty: item.my_first_string.is_empty(),
my_second_string: item.my_first_string,
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.