Best way to copy Option<&T>

What is the best way to write this function?

fn first(mut opt: Option<&mut String>) {
    match &mut opt {
        Some(v) => {
            second(Some(v));
        }
        None => {
            second(None);
        }
    }
    match &mut opt {
        Some(v) => {
            second(Some(v));
        }
        None => {
            second(None);
        }
    }
}
fn first(mut opt: Option<&mut String>) {
    for _ in 0..2 {
        second(opt.as_deref_mut())
    }
}

Option::as_deref_mut lets you reborrow the Option<&mut String>, so that you don't move it within the loop. And the loop prevents code duplication.

Option has a ton of tiny useful functions like this, so it's super helpful to look through the docs for Option to see what's there.

2 Likes

Thank you. The loop is not applicable in my case, but as_dere_mut is what I was looking for.

1 Like

Btw, if you click the pencil icon at the bottom right of your posts, you can edit your posts.

Yes, I know.

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.