5 Generics, option, and result

 

This chapter covers

  • Generics—when to use more than one type
  • Option—when an operation might produce a value but might not
  • Result—when an operation might succeed but might not

Rust is a strict language with concrete types, but after this chapter, you’ll have three important tools to work with. Generics let you describe to Rust “some sort of type” that Rust will turn into a concrete type without you having to do it. After that, we’ll learn about two interesting enums called 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 might go wrong.

5.1 Generics

We’ve known since chapter 1 that Rust needs to know the concrete type for the input and output of a function. The following return_item() function has i32 for both its input and output, and no other type will work—only i32:

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

But what if you want the function to accept more than 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 {  }      #1

You can use generics for this. Generics basically 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

Summary

sitemap