Moving array values โ€‹โ€‹between enumeration changes

My problem is as follows. I have an enum with multiple choices that use an increasing number of elements. For simplicity, I'll reduce the numbers to the first two:

#[derive(Debug)]
pub enum Variant<A> {
    Single([A; 1]),
    Double([A; 2]),
}

      

I want to create custom methods that preferentially convert Single

to Double

. For example, if I call push_front(a)

on Single([x])

, I need to return Double([a,x]

. One way to do it:

impl<A: Copy> Variant<A> {
    fn push_front(&mut self, value: A)  {
        self* = match self {
            &mut Single(b) => Double([value, b[0]]),
            _ => panic!("Can't convert"),
        };            
    }
}

      

Is there a way to achieve a similar effect without A

having to implement Copy

?

Game board link: http://is.gd/i0bQtl

+3


source to share


2 answers


You can change the limit from Copy

to Clone

; then the hand of the match becomes:



&mut Single(ref b) => Double([value, b[0].clone()]),

      

+1


source


At night, you can use the "slice_pattern" syntax:

Single([one]) => Double([value, one]),

      



PlayPen

+1


source







All Articles