Reputation: 1
Given the following code which compiles,
let alerts : Vec<Alert> = serde_json::from_value::<Vec<Alert>>(json)
.unwrap();
How come adding a .sort_by_key
results in an error
expected struct `Vec`, found `()`
Code that generated the error is,
let alerts : Vec<Alert> = serde_json::from_value::<Vec<Alert>>(json)
.unwrap()
.sort_by_key( |e| e.pub_millis );
Upvotes: 0
Views: 432
Reputation: 1660
From the documentation for Vec:
pub fn sort_by_key<K, F>(&mut self, f: F) where
F: FnMut(&T) -> K,
K: Ord
This function doesn't have a return value, and will instead sort the slice in-place. It therefore can't be used as a chained function, and must be given a mutable value. If you'd like the alerts variable to be immutable, you can use the Temporary mutability idiom to make it mutable only long enough to sort it. https://rust-unofficial.github.io/patterns/idioms/temporary-mutability.html
Upvotes: 3