今天我尝试在 LeetCode 上解决一个问题.这是我的代码(Playground):
#[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()
}
我认为代码可以 self 解释。我收到此错误消息:
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
值。有固定密码:Playground
我还提前解析了值,并在matche
es中添加了_
分支,因为它应该是详尽无遗的。理想情况下,您也不需要 match
。
更新:同一代码的更短版本:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a9a344c64f42332eb26f2a68fa260f72
关于rust - 无法从 `i32` 构建类型为 `std::iter::Iterator<Item=_>` 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58042483/