簡體   English   中英

我可以在不調用 .clone() 的情況下在類型轉換期間重用結構字段嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM