Evan Carroll
Evan Carroll

Reputation: 1

Rust adding .sort_by generates error: expected struct `Vec`, found `()`

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

Answers (1)

transistor
transistor

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

Related Questions