rust - 计算向量中最长的字符数组
问题描述
我有一个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
结构似乎没有实现共同的特征?
解决方案
Chars
do 实现了特征(因此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
迭代器只是一对指针。因此,复制是在这对整数值而不是整个底层字符串上执行的。
推荐阅读
- python - 如何在 MacOs Big Sur 上使用 Tkinter 更改按钮的背景颜色
- python - 如何在将 fft 应用于原始信号时防止过度平滑
- python - __str__ 返回非字符串(字节类型)
- r - 在 R 中创建 Fama French 3 因素回归循环
- java - 如何在 Dynamics 365 Finance and Operations 中删除具有特殊字符的 DataEntity 条目
- python - 在 VM 上运行浏览器(非无头)
- javascript - 您能否解释一下为什么我们需要检查“DELETE”请求的状态是否为 200,以及为什么我们不必对“PUT”请求进行检查?
- swift - UICollectionViewListCell 附件顶部尾随放置
- sql - X 轴条形图 Grafana 上的标签
- php - Smarty::$_tpl_vars - 未定义属性 - Smarty 3 中支持 _tpl_vars