rust - 不能从 `std::iter::Iterator 构建类型为 `i32` 的集合- `
问题描述
今天我尝试解决LeetCode上的一个问题。这是我的代码(游乐场):
#[test]
fn basic_test() {
assert_eq!(day_of_year("2019-01-09".to_string()), 9);
assert_eq!(day_of_year("2019-02-10".to_string()), 41);
assert_eq!(day_of_year("2003-03-01".to_string()), 60);
assert_eq!(day_of_year("2004-03-01".to_string()), 61);
}
pub fn day_of_year(date: String) -> i32 {
let vec: Vec<&str> = date.split("-").collect();
[(vec[0],vec[1],vec[2])].iter().map(|(year,month,day)|
match month {
&"01" => day.parse().unwrap(),
&"02" => day.parse().unwrap() + 31,
_ => match year.parse().unwrap(){
y if y%4==0&&y%100!=0
||y%400==0&&y%3200!=0
||y%172800==0=>
match month {
&"03" => day.parse().unwrap()+31+29,
&"04" => day.parse().unwrap()+31+29+31,
&"05" => day.parse().unwrap()+31+29+31+30,
&"06" => day.parse().unwrap()+31+29+31+30+31,
&"07" => day.parse().unwrap()+31+29+31+30+31+30,
&"08" => day.parse().unwrap()+31+29+31+30+31+30+31,
&"09" => day.parse().unwrap()+31+29+31+30+31+30+31+31,
&"10" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30,
&"11" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30+31,
&"12" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30+31+30
},
_ => match month{
&"03" => day.parse().unwrap()+31+28,
&"04" => day.parse().unwrap()+31+28+31,
&"05" => day.parse().unwrap()+31+28+31+30,
&"06" => day.parse().unwrap()+31+28+31+30+31,
&"07" => day.parse().unwrap()+31+28+31+30+31+30,
&"08" => day.parse().unwrap()+31+28+31+30+31+30+31,
&"09" => day.parse().unwrap()+31+28+31+30+31+30+31+31,
&"10" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30,
&"11" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30+31,
&"12" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30+31+30
}
}
}
).collect()
}
我认为代码可以自我解释。我收到此错误消息:
error[E0277]: a collection of type `i32` cannot be built from an iterator over elements of type `_`
--> src/lib.rs:45:7
|
45 | ).collect()
| ^^^^^^^ a collection of type `i32` cannot be built from `std::iter::Iterator<Item=_>`
|
= help: the trait `std::iter::FromIterator<_>` is not implemented for `i32`
我尝试将其更改为collect::<Vec<i32>>[0]
. 但仍然得到编译错误。让我知道如何更改代码以使其编译。
解决方案
您根本不需要遍历元组并调用collect
。它创建了一个集合,但您的目标只是一个i32
值。有固定的代码:游乐场
我还提前解析了值并_
在es中添加了分支,matche
因为它应该是详尽的。理想情况下,您也不需要match
。
更新:相同代码的较短版本:https ://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a9a344c64f42332eb26f2a68fa260f72
推荐阅读
- excel - Excel VBA IE 自动化 - VBA 在 Window.confirm 弹出后停止
- python - 如何使用数组找到前 n 个负整数
- css - 如何阻止 flex 行的第二行出现在页面中间?
- php - 更改 Apache http.conf 文件中的 documentroot 会停止 PHP 解析
- javascript - 如何在文本输入中添加 4 个带空格的字母数字?
- r - 无法对 word、PDF 和 HTML 执行 R 降价
- javascript - 为什么我的 vue 组件的宽度报告“未定义”?
- beautifulsoup - 如何使用 BeautifulSoup 创建带有孩子的 xml 树
- jquery - 使用 jquery 从输入字段更改名称的一部分
- r - 通过创建新变量来堆叠数据集