Rustlings: Live!

Goals:

Share knowledge

Ask Questions

Pair

Grow

Social Rules

https://www.recurse.com/manual

Have Fun!

What is an optional?

Rust doesn't have a concept of "null".

 

However, Rust has an enum that can encode the concept of a value being present or absent. This enum is Option<T>

Option Enums

enum Option<T> {
    Some(T),
    None,
}

 <T> means the Some variant of the Option enum can hold one piece of data of any type.

Why use an optional?

  • Handle null/empty values

  • Handle optional arguments

Why use an optional?

fn get_full_name(
    firstName: &str
    lastName: &str
) -> String {
    ...
}

fn get_full_name_with_middle(
    firstName: &str,
    middleName: &str,
    lastName: &str
) -> String {
    ...
}

...

Why use an optional?

fn get_full_name(
    firstName: &str,
    middleName: Option<&str>,
    lastName: &str
,
) -> String {
    ...
}
get_full_name("Leela", None, "Turanga")

What is a result?

Result is a richer version of the Option type that describes possible error instead of possible absence.

What is a result?

Result<T, E>

Ok(T) 
Err(E)
fn get_status(username: &str) -> Result<&str, String> {
    // some user lookup code here...
    if username != "janedoe" { 
        return Err("Not found".to_string());
    }
    // if user exists, fetch their status
    Ok("User is active")
}

fn main () {
    let result = get_status("janedoe");
    match result {
        Ok(status) => println!("{}", status),
        Err(e) => println!("{}", e),
    }
} 

What is a result?

What is a result?

Let's Pair!

Rustlings

https://github.com/rust-lang/rustlings

Rustlings

Result and Error

$ rustlings run option1 
$ rustlings hint option1
Complete Exercises 
option 1, 2
error_handling

Rustlings: Live! Optionals

By shortdiv

Rustlings: Live! Optionals

We cover optionals

  • 487