我目前有两个类似的 struct ,我需要实现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,
        }
    }
}

Rust相关问答推荐

如何将`Join_all``Vec<;Result<;Vec<;Foo&>;,Anywhere::Error&>;`合并到`Result<;Vec<;Foo&>;,Anywhere::Error&>;`

为什么BitVec缺少Serialize trait?

我可以在不收集或克隆的情况下,将一个带有Item=(key,val)的迭代器拆分成单独的key iter和val iter吗?

使用关联类型重写时特征的实现冲突

什么时候使用FuturesOrdered?

为什么AsyncRead在Box上的实现有一个Unpin特征绑定?

如何将带有嵌套borrow /NLL 的 Rust 代码提取到函数中

使用占位符获取用户输入

Rust 文件未编译到 dll 中

Button.set_hexpand(false) 不会阻止按钮展开

Google chrome 和 Apple M1 中的计算着色器

Rust:为什么 Pin 必须持有指针?

OpenGL 如何同时渲染无纹理的四边形和有纹理的四边形

Rust typestate 模式:实现多个状态?

如何在 Rust 中编写修改 struct 的函数

在 FFI 的上下文中,未初始化是什么意思?

Rust 中的通用 From 实现

带有库+多个二进制文件的Cargo 项目,二进制文件由多个文件组成?

你能用 Rust 和 winapi 制作 Windows 桌面应用程序吗?

为什么这里需要类型注解?