#Optional Parameters

13 messages · Page 1 of 1 (latest)

flint dew
#

Is the Rust compiler smart enough to know to optimise optional parameters away?

fn foo(value: i32) {
    ...
}

fn foo_optional(optional: Option<i32>) {
    foo(optional.unwrap_or(5));
}

fn main() {
    foo_optional(None);
    foo(5);
}

Essentially, is foo(5) the exact same thing as foo_optional(None) where optional is known to be None at compile-time?

placid urchin
#

that'll all get inlined, so sure

flint dew
#

any situations where this wouldn't work?

#

e.g.

#
#[inline(never)]
fn foo(value: i32) {
    ...
}

#[inline(never)]
fn foo_optional(optional: Option<i32>) {
    foo(optional.unwrap_or(5));
}

fn main() {
    foo_optional(None);
    foo(5);
}
placid urchin
#

maybe if it involved trait objects and dynamic dispatch etc, because those probably wont get devirtualized

placid urchin
flint dew
#

i see, i see....

#

thank you!!

ionic apex
#

I think generally it's preferred to have two distinct versions of a function if a parameter is going to be optional, for example, Vec::new and Vec::with_capacity, rather than passing Options around...

flint dew
#

Yeah, I prefer that too, I was just wondering about this case

#

I've seen this recommended as a way of doing optional parameters