Demiu
Demiu

Reputation: 309

"Move" mutable reference into itself

I am trying to implement a "transform" function that takes a non-copy enum value and and modifies it based on a parameter, but some of the parameters do nothing. A simplified example is:

enum NonCopy {
    A,
    B,
    C
}

fn transform(to_transfrom: &mut NonCopy, param: u32) -> () {
    *to_transfrom = match param {
        // transformations
        1 => NonCopy::A,
        2 => NonCopy::B, 
        // retains the value
        _ => *to_transfrom
    };
}

I know that since the NonCopy doesn't implement the Copy trait the value inside to_transform cannot be moved out, however if param is neither 1 or 2 the value of *to_transform is assigned to itself, so it stays the same and nothing should be moved, but the compiler doesn't recognize that.

How can I achieve such a pattern with an assignment to a match expression?

I know I could instead assign in the match expression, but the non-example version is bigger and I do not want to repeat so much code plus it is quite ugly.

Upvotes: 2

Views: 441

Answers (1)

Coder-256
Coder-256

Reputation: 5618

A neat little trick in Rust is that when you break out of an expression (via return, break, etc.), you don't actually need to provide a value for that expression. In this case, you can return from the match arm without providing a value:

enum NonCopy {
    A,
    B,
    C
}

fn transform(to_transfrom: &mut NonCopy, param: u32) -> () {
    *to_transfrom = match param {
        // transformations
        1 => NonCopy::A,
        2 => NonCopy::B, 
        // retains the value
        _ => return,
    };
}

Upvotes: 3

Related Questions