【发布时间】:2019-09-21 17:17:37
【问题描述】:
今天我尝试解决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()
}
我认为代码可以自我解释。我收到此错误消息:
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]。但仍然得到编译错误。让我知道如何更改代码以使其编译。
【问题讨论】:
-
您好,这里有一些关于如何在 SO 上提出更好问题的快速提示。 (a) “我认为代码可以自我解释。” -> 用几句话解释它永远不会有坏处。 (b) 将完整的代码和完整的错误消息添加到您的帖子中(就像我现在为您所做的那样)。 (c) 告诉我们您对错误的什么不了解。 (d) 发帖前尽量简化代码,搜索词minimal reproducible example。一般来说:表现出你关心,否则你不能指望别人关心。
标签: rust