Daniel Fath
Daniel Fath

Reputation: 18069

Moving array values between enum variations

My problem is following. I have enum with several variants that use increasing number of items. For simplicity I'll reduce the numbers to first two:

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

I want to create special methods which would preferably transform Single into Double. For example if I call push_front(a) on Single([x]) I need to get back Double([a,x]. One way I could do it is:

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 similar effect without A having to implement Copy?

Playground link: http://is.gd/i0bQtl

Upvotes: 3

Views: 134

Answers (2)

oli_obk
oli_obk

Reputation: 31193

On nightly you can use the "slice_pattern" syntax:

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

PlayPen

Upvotes: 1

DK.
DK.

Reputation: 59015

You could change the constraint from Copy to Clone; then, the match arm would become:

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

Upvotes: 1

Related Questions