首页 > 解决方案 > 计算向量中最长的字符数组

问题描述

我有一个char_vec: &Vec<Chars>作为参数的函数。我知道每个的长度Chars可能不同 - 我想得到最长的长度。我正在尝试使用以下代码来做到这一点:

let longest = char_vec.iter().map(|x| x.count()).max().unwrap_or(0);

不幸的是,这失败并出现以下错误:

error[E0507]: cannot move out of `*x` which is behind a shared reference
  --> C:\Rust\playground\src\lib.rs:62:43
   |
62 |     let longest = char_vec.iter().map(|x| x.count()).max().unwrap_or(0);
   |                                           ^ move occurs because `*x` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait

我真的不明白如何在count()这里执行该方法。该Chars结构似乎没有实现共同的特征?

标签: rust

解决方案


Charsdo 实现了特征(因此Iterator它可以使用它的方法)。这里count接受self按值的问题,即有签名Iterator::count(self) -> usize。另一方面,iter您调用了对引用的迭代,即 over&Chars而不是Chars. 因此,您需要将项目转换为拥有的项目,即:

use std::iter::Iterator;
let longest = v.iter().cloned().map(Iterator::count).max().unwrap_or(0);

// you may also do the same with each item explicitly:
let longest = v.iter().map(|x| x.clone().count()).max().unwrap_or(0);

请记住,克隆是一个相当便宜的操作(以及大多数其他迭代器)。Chars迭代器只是一对指针。因此,复制是在这对整数值而不是整个底层字符串上执行的。


推荐阅读