2

I have a struct of the shape

pub struct ExampleData {
    data: Vec<u32>,
    data_ids: Vec<u32>,
}

Sample data

{data: [9,8,7], data_ids: [0,1,2]}

I want to sort the data_ids vector based on the values of the data vector and I have implemented the following method:

impl ExampleData {
    pub fn sorting(&mut self) {
        self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
    }
}

The above code does not work:

error[E0277]: the type `[u32]` cannot be indexed by `&u32`
  --> src/lib.rs:10:38
   |
10 |         self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
   |                                      ^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[u32]>` is not implemented for `&u32`
   = note: required because of the requirements on the impl of `Index<&u32>` for `Vec<u32>`

What am I doing wrong here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ankit
  • 31
  • 4
  • 1
    [The duplicates applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e2cd3edf39f1fb1319b70e572e75add9), but I'd encourage [using `sort_by_key` instead](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=862fb35ee7d2d64be3a1de7c9ac4f54f). – Shepmaster Mar 29 '21 at 16:33
  • 1
    Thanks for the quick response, works like a charm. – Ankit Mar 29 '21 at 16:44

0 Answers0