根据值选择

trait Select<T>{
    fn select<'a>(self, slice:&'a Vec<T>)->Vec<&T>;
}

impl<T> Select<T> for usize {
    fn select<'a>(self, slice:&'a Vec<T>)->Vec<&T> {
        match slice.get(self) {
            Some(x)=>vec![x],
            None => vec![]
        }
    }
}

impl<T, const N:usize> Select<T> for [usize;N] {
    fn select<'a>(self, slice:&'a Vec<T>)->Vec<&T> {
        let mut r:Vec<&T> = vec![];
        for i in self.into_iter(){
            match slice.get(i.clone()) {
                Some(x) => r.push(x),
                None => {}
            }
        }
        r
    }
}


fn main(){
    let a: Vec<u32> = vec![2,5,6,7,3,2,2,1,100];
    println!("{:?}", Select::select([1,2,3], &a));
    println!("{:?}", Select::select(3, &a));
}

  

posted @ 2022-07-16 23:41  CrossPython  阅读(15)  评论(0编辑  收藏  举报