3

Rust has a method on an enum called .map_or_else() it takes two closures one of which triggers on None, the other triggers on Some(inner) passing inner.

This is great, but what I want to do is move a value into both branches of it. This generates an error,

error[E0382]: borrow of moved value: `result` --> src/sequence/renderer.rs:124:5 | 104 | let result = match self.display { | ------ move occurs because `result` has type `String`, which does not implement the `Copy` trait ... 123 | || Ok(result), | -- ------ variable moved due to use in closure | | | value moved into closure here 124 | |v| Ok(format!("{:0>width$}", result.clone(), width=v as usize )) | ^^^ ------ borrow occurs due to use in closure | | | value borrowed here after move) 

This error can be be solved by replacing the first closure to .map_or_else with,

Ok(result.clone()) 

But is this a good idea? Then I have to clone() a string for no benefit? What is the idiomatic way to use .map_or_else() when both sides need access to the same variable?

1
  • 1
    The format! doesn't require an owned value: a borrowed value work just as well (it allocates a new String itself anyway). But you'd still be better off moving into the first closure, so that observation doesn't actually help here. Commented Sep 14, 2021 at 8:22

1 Answer 1

8

Unfortunately there is no way for this to work, since Rust has no way of annotating the two closures as "only one will get invoked".

So your best bet is to not use the higher-level function and instead write a simple match expression.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.