Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving array values between enum variations

Tags:

rust

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

like image 236
Daniel Fath Avatar asked May 07 '26 14:05

Daniel Fath


2 Answers

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

&mut Single(ref b) => Double([value, b[0].clone()]),
like image 66
DK. Avatar answered May 10 '26 11:05

DK.


On nightly you can use the "slice_pattern" syntax:

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

PlayPen

like image 26
oli_obk Avatar answered May 10 '26 12:05

oli_obk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!