@Ambraven@social.mochi.academy
Post #2564767
2026-04-29 15:47 UTC
Replies (5)
-
@Ambraven@social.mochi.academy 2026-04-30 08:07
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
-
@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?
-
@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
-
@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); } }
-
@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.