How to init a generic array in rust?

   #[derive(Debug)]
    struct MaxPQ<T: Ord + Copy> {
        pq: Box<[T]>,
        N: usize,
    }

impl<T: Ord + Copy> MaxPQ<T> {
    fn new(max_N: usize) -> Self {
        //I want sth like this:
        //let pq=Box::new([T;max_N]);
        //or :
        //let pq = vec![Box::new(T); max_N].into_boxed_slice();
        Self { pq, N: max_N }
    } 
}

i don't want to use vec,so is it possiable to get that?

You must put some value into the slice. One option would be to:

impl<T: Ord + Copy> MaxPQ<T> {
    fn new(max_N: usize, init: T) -> Self {
        let pq = vec![init; max_N].into_boxed_slice();
        Self { pq, N: max_N }
    } 
}

thank you very much ~

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.