下面是我的一个leetcode问题的代码:
pub fn group_strings(strings: Vec<String>) -> Vec<Vec<String>> {
let mut strings_iter = strings.into_iter();
// Unwrap because the pblm guarantees that strings len >= 1
let mut result = vec![vec![strings_iter.next().unwrap()]];
let mut seq_found: bool = false;
while let Some(input_string) = strings_iter.next() {
// Is this string in seq with any of the strings in the result?
for output_string_list in result.iter_mut() {
if Solution::are_in_seq(&output_string_list[0], &input_string) {
// We are cloning because rust complains that we are using input_string
// after it is moved here, although seq_found flag ensures that we don't.
output_string_list.push(input_string);
seq_found = true;
break;
}
}
if !seq_found {
result.push(vec![input_string]);
}
seq_found = false;
}
return result;
}
字符串
我得到的编译器错误是:
Line 22, Char 34: use of moved value: `input_string` (solution.rs)
|
9 | while let Some(input_string) = strings_iter.next() {
| ------------
| |
| this reinitialization might get skipped
| move occurs because `input_string` has type `std::string::String`, which does not implement the `Copy` trait
...
15 | output_string_list.push(input_string);
| ------------ value moved here
...
22 | result.push(vec![input_string]);
| ^^^^^^^^^^^^ value used here after move
For more information about this error, try `rustc --explain E0382`.
型
我只在seq_found
的情况下推送input_string
。但是编译器会将其标记为move后可能使用。告诉编译器我处理了这种情况的最佳方法是什么?为了解决这个问题,我可以这样做:
output_string_list.push(input_string.clone());
型
但这个克隆是不必要的,可能是一个昂贵的操作。
2条答案
按热度按时间kqqjbcuj1#
是的,通过使用控制流结构(编译器可以理解),而不是
bool
s的值(编译器不理解)。使用带标签的循环,你可以continue
循环,编译器理解这会阻止循环体的其余部分执行,同样地,如果我们不continue
,我们永远不会消耗input_string
,因为它们发生在同一块中。字符串
(顺便说一句,这段代码也要短得多,而且少了一个变量。
wvyml7n52#
不使用
for
,这可能会混淆您的控制流,您可以使用一些迭代器操作来首先查找匹配列表,然后根据是否找到匹配来移动input_string
:字符串