How can I create a function that use:
- Default parameters
- Optional arguments.
How can I create a function that use:
There is no way to specify default parameter values in Rust, but there is an RFC for it. For now you just have to handle this need ad-hoc in whatever way makes sense for your use case.
Take an Option<Foo>
.
Well, the closest we have to this in rust is Option
s. Default values:
fn foo(possibly_supplied: Option<usize>) {
let x = possibly_supplied.unwrap_or(20); //Default value is 20
}
And for optional arguments, the above is the closest thing, except you handle None
values differently:
fn foo(optionally_supplied: Option<usize>) {
if let Some(x) = optionally_supplied {
// A value
else {
// No value
}
}
Unfortunately, you can't do things like you can in other languages (In this case C#):
public static int Foo(int x = 0) => 20 * x;
public static int Foo() => 10;
I found this as potential solution, liked to share with the community:
struct
and impl Default
example:
use std::default::Default;
#[derive(Debug)]
pub struct Sample {
a: u32,
b: u32,
c: u32,
}
impl Default for Sample {
fn default() -> Self {
Sample { a: 2, b: 4, c: 6}
}
}
macro_rules! five_times {
($x:expr) => (5 * $x);
() => (5);
}
fn main() {
let s = Sample { c: 23, .. Sample::default() };
println!("{:?} {:?}", s, five_times!());
}
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.