<ao> | Adetunji's Blog

Option, Something might or might not exist

Consider the code below:

fn main(){
    let my_vec = vec![2,6,8];
    return_fifth(my_vec);
}

fn return_fifth(value: Vec<i32>) -> Vec<i32>{
    value[5]
}

This will cause the compiler to panic. We can avoid that by utilizing Option. Option gives us the ability to specify what we want to do if a value exists or not, giving us proper control of how our code runs.

fn main(){
    let my_vec = vec![2,6,8];
    let my_vec = vec![2,6,8,56,78];
    return_fifth(my_vec);
}

fn return_fifth(value: Vec<i32>) -> Option<i32>{
    if value.len() < 5{
	None
    }else{
	Some(value[5])
    }
}

This returns None and Some(78), there's no panic anymore, how do we get to the value inside Some, we can use the unwrap function. But we also don't want to unwrap a None as that would result in an error.

A match pattern can save us here.

fn main(){
    let small = vec![2,6,8];
    let big = vec![2,6,8,56,78];
    let mut new_vec = Vec::new();
	
    new_vec.push(return_fifth(small));
    new_vec.push(return_fifth(big));

    do_check(&new_vec)
}

fn return_fifth(value: Vec<i32>) -> Option<i32>{
    if value.len() < 5{
	None
    }else{
	Some(value[5])
    }
}

fn do_check(options_vec: &Vec<Option<i32>>){
    for item in otion_vec{
	match item{
	    Some(number) => println!("We have some {}", number),
	    None => println!("We got none"),
	}
    }
}

We are able to get the value in Some this way but Option has few methods that check for the presence of Some and None;

Then we can do away with the do_check() and safely use unwrap() as we will perform the check if some exist before unwrapping its value.

fn main(){
    let small = vec![2,6,8];
    let big = vec![2,6,8,56,78];

    for vec in !vec[small, big]{
    let inner_vec = return_fifth(vec)
    if inner_vec.is_some(){
	println!("Yay!, got {}", inner_vec.unwrap())
    }else{
         println!("Got None here")
	}
    }
	
}

fn return_fifth(value: Vec<i32>) -> Option<i32>{
    if value.len() < 5{
	None
    }else{
	Some(value[4])
    }
}

And Option is just an enum, it has the signature:

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

#note #rust