What I am trying to do is to implement a strategy
pattern in Rust. In this example I have several sorting algos that I've coded:
use std::cmp::{ Ord, Ordering };
pub trait Sorter {
fn sort<T>(arr: &mut Vec<T>, desc: bool) where T: Ord + Copy;
}
pub struct BubleSort;
pub struct SelectionSort;
impl Sorter for BubleSort {
fn sort<T>(arr: &mut Vec<T>, desc: bool) where T: Ord + Copy{
...
}
}
impl Sorter for SelectionSort {
fn sort<T>(arr: &mut Vec<T>, desc: bool) where T: Ord + Copy{
...
}
}
Then I want to pass one of them to a function to use it. Something like this:
fn sort<T>(sorter: dyn Sorter, arr: &mut Vec<T>) {
sorter::sort(arr);
}
Also is it possible to add them in lets say a Vec and iterate over it, so I can call the functions from there?
Is this possible, or do I need to make instances of the structs and use methods instead?