gpt4 book ai didi

rust - 使用结构文字更新语法时无法移出借用的内容 : User { active: false, ..*user }

转载 作者:行者123 更新时间:2023-11-29 08:25:03 25 4
gpt4 key购买 nike

我刚开始使用 Rust,我非常喜欢 ..create an instance of another instance 的语法但我不知道如何将它与实例引用一起使用。

Try it here.

#[derive(Debug)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}

fn main() {
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
let user2 = foo(&user1);

println!("{:?}", user2);
}

fn foo(user: &User) -> User {
User {
active: false,
..*user
}
}

这给了我错误:

error[E0507]: cannot move out of borrowed content
--> src/main.rs:24:11
|
24 | ..*user
| ^^^^^ cannot move out of borrowed content

有趣的是它在某些时候对我有用:

fn reduce<'a>(state: &State<'a>, action: Action) -> Option<State<'a>> {
match action {
Action::LoadRoms { roms } => {
let mut new_state = State { roms, ..*state };
Some(new_state)
}
_ => None,
}
}

From here.

最佳答案

..expr 语法将所有缺失的成员从 expr 移走。它移动。这意味着您通常不能将它与引用一起使用,因为您不能移出引用(不过您可以将 Copy 类型“移出”引用)。

要解决您的问题,您需要克隆,以便获得一个新的完整对象,您可以从中移动:

fn foo(user: &User) -> User {
User {
active: false,
..user.clone()
}
}

( link to playground )

缺点是这也会克隆所有不需要的成员,因为您已经指定了它们。在这种情况下它很好,因为克隆 active 是一个微不足道的操作(因为它只是一个 bool 值),但是这会为 username 创建一个额外的无用克隆:

fn foo(user: &User) -> User {
User {
username: "foo".into(),
..user.clone()
}
}

关于rust - 使用结构文字更新语法时无法移出借用的内容 : User { active: false, ..*user },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com