Hello everyone,
Another newbie question from me.
Consider this snippet of code:
use chrono::{DateTime, Utc};
#[derive(PartialEq, Debug)]
struct DealEvent {
pub r#type: String,
pub value: String,
pub inserted_at: DateTime<Utc>,
}
fn filter_by_type(deal_events: Vec<DealEvent>) -> Vec<DealEvent> {
let result = deal_events
.into_iter()
.filter(|e| e.r#type == String::from("new"))
.collect();
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filter_by_type_filters_by_type() {
let bad_de = DealEvent {
r#type: String::from("foo"),
value: String::from("bar"),
inserted_at: Utc::now(),
};
let good_de = DealEvent {
r#type: String::from("new"),
value: String::from("bar"),
inserted_at: Utc::now(),
};
let result = filter_by_type(vec![bad_de]);
assert_eq!(result, vec![]);
let result = filter_by_type(vec![good_de]);
assert_eq!(result, vec![good_de]);
}
}
This snippet produces the following error:
error[E0382]: use of moved value: `good_de`
--> src/lib.rs:45:29
|
35 | let good_de = DealEvent {
| ------- move occurs because `good_de` has type `DealEvent`, which does not implement the `Copy` trait
...
44 | let result = filter_by_type(vec![good_de]);
| ------- value moved here
45 | assert_eq!(result, vec![good_de]);
| ^^^^^^^ value used here after move
I conceptually understand what the error is about, but I'm not sure how to fix it. I'd tried adding the Copy and Clone traits to the struct, but it seems that Copy is not implemented for String types, so that didn't work.
I would really appreciate if someone can help me not only fix this, but explain why this is happening, so I can better understand how the compiler thinks.
Thank you!
P.S. As a secondary question — is there a way not to do I figured this out just now — I put semicolon in the end after let result = ... and then return result in the filter_by_type function? I tried using the chain of functions directly, but then the compiler complained that the expected return type was () ![]()
collect() which made the function return () rather than the Vec ![]()