tleyden
tleyden

Reputation: 1980

How do I create a vector of functions with generic type parameters?

I have a few functions with the same generic type signature:

pub fn selection_sort<T: Ord + Debug>(v: &mut [T]) {}

pub fn insertion_sort<T: Ord + Debug>(v: &mut [T]) {}

I want to put them into a Vec or array so that I can iterate over them and run the same tests on them, as follows:

let mut sorters: Vec<fn<T: Ord + Debug>(v: &mut [T])> = Vec::new();

However I get this compiler error:

error: expected `(`, found `<`
 --> src/main.rs:8:28
  |
8 |     let mut sorters: Vec<fn<T: Ord + Debug>(v: &mut [T])> = Vec::new();
  |         -----------        ^
  |         |
  |         while parsing the type for `mut sorters`

How can I put these functions into a vector? Is there a better approach to re-use tests against functions that satisfy this signature?

I'm using Rust 1.24.0.

Upvotes: 2

Views: 1369

Answers (1)

Shepmaster
Shepmaster

Reputation: 432049

You cannot have a function pointer with a generic type. You will need to pick a specific type for T:

use std::fmt::Debug;

pub fn selection_sort<T: Ord + Debug>(v: &mut [T]) {}

pub fn insertion_sort<T: Ord + Debug>(v: &mut [T]) {}

fn main() {
    let sorters_u8: &[fn(&mut [u8])] = &[selection_sort, insertion_sort];
    let sorters_bool: &[fn(&mut [bool])] = &[selection_sort, insertion_sort];
}

The intuition here is that a function pointer has to point to something. Until a specific type has been provided to the function, there isn't any actual code generated — the compiler cannot create an infinite number of functions just in case one of them is chosen later.

See also:

Upvotes: 4

Related Questions