-1

I have ks: Vec<(Vec<u64>, U)> that I would like to sort by the tuple's 1st element's sum. How do I do that?

I tried this

ks.sort_by_key(|k| k.0.iter().sum());

But this gives me the error message

type annotations needed
cannot infer type for type parameter `K` declared on the associated function `sort_by_key` (rustc E0282)
: consider specifying the type argument in the method call: `::<S>`
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48

1 Answers1

0

You need to specify the return type of the closure that you are sorting after. Changing your code to this will work:

ks.sort_by_cached_key::<u64, _>(|k| k.0.iter().sum());
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
  • 1
    I'd suggest using `sort_by_cached_key` instead of `sort_by_key` as the sum remains stable while sorting and would otherwise get recomputed on every pairwise comparison. – user2722968 Jan 20 '22 at 11:04