Value consumed by multiple try_from (design pattern)

Hello,
I'm trying to implement multiple try_from with enum, but the value is consumed by the try_from function.
Is there an elegant way to implement this kind of pattern without clone() ?
I could use reference but the Foo struct is used in Bar1/Bar2

fn main() {
    let foo = Foo{};
    let _bar: BarKind = if let Ok(bar1) = Bar1::try_from(foo) {
        BarKind::Bar1(bar1)
    } else {
        BarKind::Bar2(Bar2::try_from(foo).unwrap())
    };
}
Compiling playground v0.0.1 (/playground)
error[E0382]: use of moved value: `foo`
  --> src/main.rs:45:38
   |
41 |     let foo = Foo{};
   |         --- move occurs because `foo` has type `Foo`, which does not implement the `Copy` trait
42 |     let _bar: BarKind = if let Ok(bar1) = Bar1::try_from(foo) {
   |                                                          --- value moved here
...
45 |         BarKind::Bar2(Bar2::try_from(foo).unwrap())
   |                                      ^^^ value used here after move

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` due to previous error

I would like to keep the complex matching logic inside the TryFrom but something is wrong in my design.
Thank you a lot for your help

String::from_utf8 returns the Vec to the caller in the error case by including it in the error value. This is a pretty common pattern for fallible conversion methods that take a parameter by value

1 Like

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.