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.
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