How Default Values and Optional Parameters work in Rust

Money Grows on Trees
2 min readJul 3, 2020
Photo by Francois Olwage on Unsplash

Have you ever wanted to define default values for your structs, read below to learn how

Let’s define a struct type A with 3 fields

struct A {
val_b: u32,
val_c: u32,
val_d: u32
}

Below is how we implement the Default Trait for Struct A

// We need to implement the Default Trait for the Struct
impl Default for Client {
fn default() -> Self {
A {
val_b: 1,
val_c: 2,
val_d: 3
}
}
}

So if I want to create an instance of Struct A with all values set to default, we can do the following:

let object: A = Default::default();

And variable object will look like:

object = A {
val_b: 1,
val_c: 2,
val_d: 3
}

But what if I specific values I want to set for fields val_b and val_c, well then we can do the following:

let object: A = A {
val_b: 100,
val_c: 200,
..Default::default()
}

This sets the val_b & val_c to the specific values we provided but will fall back to the default value we defined in our implementation for val_d field

But what if I am also interested in specifying default function arguments

Well, Rust does not support default function arguments and nor function overloading so that means you need to create multiple methods with different names

fn connect_with_server_bucket(a: &str, b: &str)
fn connect_with_server_bucket_collection(a: &str, b: &str, c: &str)

How about using Option

We can use Option Type to specify arguments that will be passed or not

fn connect_with_server_bucket_collection(a: Option<&str>, b: Option<&str>, c: Option<&str>)

Here we might get all three parameters containing a reference to string literals or get none of them

It adds some convenience but you can see it can easily clutter the API with increasing Some and None variants of the Option floating around

--

--