Elektrine lite

← Feed

@Ambraven@social.mochi.academy

Post #2564767

2026-04-29 15:47 UTC

#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.

Replies (5)

  • So I fed some solutions into compiler explorer: https://godbolt.org/z/fadsa9q8n For reference this is what I'm trying to emulate from C++: https://godbolt.org/z/hEEodGMWG I think the "bar" version is the closest match. Also it's worth pointing out that de C++ example only worst because the foo argument is const. #rust #rustlang #Cpp

    Open ##2564768

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

    @Ambraven@social.mochi.academy are you trying to have foo be of type &A then? It's a little unclear what the objective is if not to clone?

    Open ##2564781

  • @terts@mastodon.online 2026-04-29 16:03

    @Ambraven@social.mochi.academy I think this is what you're looking for: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=6a3bfd5d1f8222236c6c77d67c29d3e5

    Open ##2564784

  • @benjamingeer@piaille.fr 2026-04-29 16:04

    @Ambraven@social.mochi.academy The problem is that if the Option is empty, you're making a new instance of A. If you take a reference to that, the A still has to stay in scope (i.e. not be dropped) while you're using the reference. You could do something like this: fn use_f(f: &A) { println!("{f:?}"); } fn toto(foo: Option) { if let Some(f) = foo { use_f(f); } else { let f = A::new(); use_f(&f); } }

    Open ##2564790

  • @rkaj@mastodon.nu 2026-04-29 16:08

    @Ambraven@social.mochi.academy Then I think you need to either let the internal foo be a Cow, or have a static A for the default. Or you _could_ create a default A any time you need it and leak it, but that will break if you call the fn many times.

    Open ##2564796