简体   繁体   English

我可以在不调用 .clone() 的情况下在类型转换期间重用结构字段吗?

[英]Can I reuse a struct field during type conversion without calling .clone()?

I currently have two similar structs, and I need to implement the From trait to convert one to the other.我目前有两个相似的结构,我需要实现From特性以将一个转换为另一个。 However, I'm getting an error that says:但是,我收到一条错误消息:

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

Here's what my code looks like:这是我的代码的样子:

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(),
        }
    }
}

I'm aware that I could just call .clone on my_first_string to satisfy the borrow checker, but this seems like it may be unnecessary.我知道我可以在my_first_string上调用.clone来满足借用检查器的要求,但这似乎是不必要的。 Is there a way to use this field twice without .clone() ?有没有办法在没有.clone()的情况下使用这个字段两次?

Just store the result of is_empty() is a variable before moving the string:在移动字符串之前,只需将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,
        }
    }
}

Or just inverse the order:或者只是颠倒顺序:

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