Elektrine lite

← Feed

@Ambraven@social.mochi.academy

Post #2147726

2026-04-29 15:09 UTC

#rust #rustlang Is there a better way to do this ? fn toto(foo: Option<&A>) { let foo = if let Some(f) = foo { f.clone() } else { A::new() } // ... use foo somehow } I can't use unwrap_or since inside the Option is a reference. I guess I could not copy the A if I set a replacement just in case but it still build an unnecessary A. Maybe the problem is using a ref in an Option in the first place? But I would like to avoid copying A or moving it if possible.

Replies (7)

  • #rust #rustlang I can't "respond to all" so I'm answering here. So you gave me clean solution to do the same as my code, so thank you. All neat. However is there a way to not clone the A passed in the option ? It feels misleading to have a function take a reference and clone the data under the hood.

    Open ##2564767

  • @emily_s@mastodon.me.uk 2026-04-29 15:12

    @Ambraven@social.mochi.academy Something like: `foo.map(|f| f.clone()).unwrap_or_else(||A::new())`

    Open ##2564769

  • @mohs@climatejustice.social 2026-04-29 15:15

    @Ambraven@social.mochi.academy depending on what you want to achieve you have different options. If A implements default you can use unwrap_or_default(). You can first clone foo, as you are cloning inside anyway. Having a ref in an option is pretty common, so you should force yourself into cloning / rc'ing.

    Open ##2564775

  • @B3NNY@infosec.exchange 2026-04-29 15:17

    @Ambraven@social.mochi.academy `let foo = foo.map(Clone::clone).unwrap_or_else(|| A::new())`

    Open ##2564777

  • @ebel@moytura.org 2026-04-29 15:20

    @Ambraven@social.mochi.academy how about `Option::map_or` / `Option::map_or_else` ? https://doc.rust-lang.org/std/option/enum.Option.html#method.map_or_else

    Open ##2564778

  • @nik@toot.teckids.org 2026-04-29 15:23

    @Ambraven@social.mochi.academy foo.cloned().unwrap_or() https://doc.rust-lang.org/std/option/enum.Option.html#method.cloned

    Open ##2564779

  • @Hemera@meow.social 2026-04-29 15:27

    @Ambraven@social.mochi.academy I'll add to the bandwagon by going shorter: foo.cloned().unwrap_or(A::new)

    Open ##2564780