错误:在Rust中使用移动值res

错误:在Rust中使用移动值res,rust,Rust,这个代码是怎么回事: fn method1(a: &str) -> (String, String) { let res = method2(a); (res.val0(), res.val1()) } 错误是: error: use of moved value res 如何修复它?看起来method2()返回一个不可复制的对象,而val0()和val1()方法按值获取目标: struct SomeType { ... } impl SomeType { f

这个代码是怎么回事:

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

error: use of moved value res

如何修复它?

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

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()
方法,没有公共字段,也没有实现
Clone
。那你就不走运了。您将只能获得
val0()
val1()
方法的结果,但不能同时获得两者

If
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
本身是一个两元素元组,您甚至不需要将
写入
,只需按原样编写
method2()
调用:

method2(a)
元组还提供元组和元组结构,而不是即将被弃用的元组。它也可用于:

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)

method2
返回一个元组
(String,String,…)
,它可以从
res.val0()
res.val1()
方法调用中看到。我怀疑是这样,但没有人阻止您将自定义
val0()
val1()
方法添加到您想要的任何数据类型,正如@PaoloFalabella在他的评论中所完美证明的那样,@Vladimitaveveveve我不小心删除了我的评论。Playpen链接再次供参考(顺便问一下,不知道它们能活多久…)Da chtozh ya sovsem uzhe iz uma vizhil chtobi dobavlyat’metodi s takimi imenami?