chapter five

5 Generics, Option, and Result

 

This chapter covers

  • Generics - When you want to use more than one type
  • Option - When an operation might produce a value, but maybe not
  • Result - When an operation might succeed, but maybe not

Rust is a strict language, but after this chapter you'll have three important tools to work with it. Generics let you describe to Rust "some sort of type" that it will turn into a strict type without you having to do it. After that you'll learn about Option and Result: Option tells Rust what to do when there might not be a value, and Result tells Rust what to do when something goes wrong.

5.1 Generics

We’ve known since Chapter 1 that Rust needs to know the type for input and output of a function. The return_number() function shown below has i32 for both:

fn return_number(number: i32) -> i32 {
    println!("Here is your number.");
    number
}
 
fn main() {
    let number = return_number(5);
}

But what if you want the function to accept more than just i32? It would be annoying if you had to write all these functions:

fn return_i32(number: i32) -> i32 {  }
fn return_i16(number: i16) -> i16 {  }
fn return_u8(number: u8) -> u8 {  }
// and so on, and so on...

You can use generics for this. Generics means "maybe one type, maybe another type".

5.2 Option and Result

5.2.1 Option

5.2.2 Result

5.2.3 Some other ways to do pattern matching

5.3 Summary