gpt4 book ai didi

rust - 错误 : use of moved value res in Rust

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

这段代码是怎么回事:

fn method1(a: &str) -> (String, String) {
let res = method2(a);
(res.val0(), res.val1())
}

错误是:

error: use of moved value res

我该如何解决?

最佳答案

看起来 method2() 返回一个不可复制的对象,而 val0()val1() 方法获取它们的目标按值(value):

struct SomeType { ... }

impl SomeType {
fn val0(self) -> String { ... }
fn val1(self) -> String { ... }
}

fn method2(a: &str) -> SomeType { ... }

fn method1(a: &str) -> (String, String) {
let res = method2(a);
(res.val0(), res.val1())
}

因为 SomeType 不是自动可复制的,它会被移动到按值获取它的方法中,但是你试图这样做两次,这是不合理的,并且编译器报告“使用移动值”错误。

如果你不能改变 SomeType 并且它只有 val0()val1() 方法,没有公共(public)字段并且没有实现 Clone。那你就不走运了。您将只能获得 val0()val1() 方法的结果,而不能同时获得两者。

如果 SomeType 也有返回引用的方法,像这样:

impl SomeType {
fn ref0(&self) -> &String { ... }
fn ref1(&self) -> &String { ... }
}

(&str 而不是 &String 也可以)然后你可以克隆字符串:

let res = method2(a);
(res.ref0().clone(), res.ref1().clone())

如果 SomeType 提供某种解构就更好了,例如:

impl SomeType {
fn into_tuple(self) -> (String, String) { ... }
}

那么就很简单了:

method2(a).into_tuple()

如果SomeType本身就是一个二元组,你甚至不需要into_tuple(),只需要写method2()调用原样:

method2(a)

元组还提供tuple indexing syntax用于元组和元组结构而不是即将弃用的 tuple traits .它还可以用于:

let res = method2(a);
(res.0, res.1)

如果 SomeType 确实是一个相同大小的元组,这是多余的,但如果 SomeType 是一个更大大小的元组,这是要走的路。或者你可以使用解构:

let (v1, v2, _) = method2(a);  // need as many placeholders as there are remaining elements in the tuple
(v1, v2)

关于rust - 错误 : use of moved value res in Rust,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27224760/

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