kepler69c
kepler69c

Reputation: 13

Giving a method as a parameter in Rust (Vec sort() method)

I can't figure out how i can give the sort method that can be found in the Vec implementation here https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort as a parameter.

My code is inspired by the code that can be found in this problem Is it possible to pass an object method as argument to a function and bind it to the object?, but won't compile.

Here is some example code of what i want to do,

fn pass_sort<F>(list: &mut Vec<i32>, sort_func: F)
    where F: Fn(&mut Vec<i32>)
{
    sort_func(list);
}

fn main() {
    let mut list: Vec<i32> = vec![3, 2, 1];
    pass_sort(&mut list, Vec::sort);
}

and here is the error

error[E0599]: no function or associated item named `sort` found for struct `std::vec::Vec<_>` in the current scope
 --> stak_test.rs:9:31
  |
9 |     pass_sort(&mut list, Vec::sort);
  |                               ^^^^ function or associated item not found in `std::vec::Vec<_>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.

I guess it happens because sort isn't a method of Vec but a method from the Deref<Target=[T]> implementation as explained in the doc, but i can't figure out how to access the method from this scope :/.

Upvotes: 1

Views: 379

Answers (1)

Kitsu
Kitsu

Reputation: 3445

I guess it happens because sort isn't a method of Vec but a method from the Deref<Target=[T]>

That is correct, the method comes from slice::sort, so you need to use it instead:

fn pass_sort<F>(list: &mut Vec<i32>, sort_func: F)
where
    F: Fn(&mut [i32]),
{
    sort_func(list);
}

fn main() {
    let mut list: Vec<i32> = vec![3, 2, 1];
    pass_sort(&mut list, <[i32]>::sort);
}

Upvotes: 1

Related Questions