如何在不复制的情况下将字符串值从数组移到元组? [英] How do I move String values from an array to a tuple without copying?
问题描述
我有一个固定大小的数组,该数组的大小为 String
s: [String; 2]
。我想将其转换为(String,String)
。
I have a fixed size array of String
s: [String; 2]
. I want to turn it into a (String, String)
. Can I do this without copying the values?
我正在特别处理的代码段如下:
The piece of code that I'm working on in particular is the following:
let (basis, names_0, names_1) = if let Some(names) = self.arg_name {
(ComparisonBasis::Name, names[0], names[1])
} else {
(ComparisonBasis::File, self.arg_file[0], self.arg_file[1])
};
类型:
self.arg_name: Option<[String; 2]>
self.arg_file: Vec<String>
现在我遇到了错误
cannot move out of type `[std::string::String; 2]`, a non-copy fixed-size array [E0508]
和
cannot move out of indexed content [E0507]
用于 if
推荐答案
您已经省略了很多上下文,所以我在几个方面进行了猜测。我也更想知道您所提出的问题,而不是您的摘录所隐含的问题。
You've omitted a fair amount of context, so I'm taking a guess at a few aspects. I'm also hewing a little closer to the question you asked, rather than the vaguer one implied by your snippets.
struct NeverSpecified {
arg_names: Option<[String; 2]>,
arg_file: Vec<String>,
}
impl NeverSpecified {
fn some_method_i_guess(mut self) -> (String, String) {
if let Some(mut names) = self.arg_names {
use std::mem::replace;
let name_0 = replace(&mut names[0], String::new());
let name_1 = replace(&mut names[1], String::new());
(name_0, name_1)
} else {
let mut names = self.arg_file.drain(0..2);
let name_0 = names.next().expect("expected 2 names, got 0");
let name_1 = names.next().expect("expected 2 names, got 1");
(name_0, name_1)
}
}
}
我使用 std :: mem :: replace
切换数组的内容,同时使其处于有效状态。这是必要的,因为Rust不允许您使用部分有效的数组。此路径没有任何副本或分配。
I use std::mem::replace
to switch the contents of the array, whilst leaving it in a valid state. This is necessary because Rust won't allow you to have a "partially valid" array. There are no copies or allocations involved in this path.
在另一路径中,我们必须手动将元素从向量中拉出。同样,您不能只是通过索引将值移出容器(实际上这是对整个索引的限制)。相反,我使用 Vec ::耗尽
基本上将向量中的前两个元素砍掉,然后从生成的迭代器中提取它们。要明确:此路径不涉及任何副本或分配,或。
In the other path, we have to pull elements out of the vector by hand. Again, you can't just move values out of a container via indexing (this is actually a limitation of indexing overall). Instead, I use Vec::drain
to essentially chop the first two elements out of the vector, then extract them from the resulting iterator. To be clear: this path doesn't involve any copies or allocations, either.
顺便说一句,那些期望
方法应该永远不会被触发(因为 drain
会进行边界检查),但是比起遗憾更好的偏执;如果您想用 unwrap()
调用代替它们,那应该没事。.
As an aside, those expect
methods shouldn't ever be triggered (since drain
does bounds checking), but better paranoid than sorry; if you want to replace them with unwrap()
calls instead, that should be fine..
这篇关于如何在不复制的情况下将字符串值从数组移到元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!