20 A tour of the standard library

 

This chapter covers

  • A more in-depth look at familiar types
  • Associated constants
  • A summary of the three associated items in Rust
  • Recently added functions such as from_fn and then_some
  • New types, such as OsString and CString

Good work! You’re almost through the book—there are only five chapters left. For this chapter and the next, we are going to sit back and relax and go on a short tour of the standard library, including further details on some of the types we already know. You will certainly end up encountering these modules and methods as you continue to use Rust, so we might as well learn them now so that they are already familiar to you. Nothing in this chapter will be particularly difficult to learn, and we’ll keep things pretty brief and run through one type per section.

20.1 Arrays

Arrays have become easier to work with over time, as we saw in the chapter on const generics. Some other nice changes have taken place that we’ll take a look at now.

20.1.1 Arrays now implement Iterator

In the past (before Rust 1.53), arrays didn’t implement Iterator, and you needed to use methods like .iter() on them in for loops. (Another method was to use & to get a slice in for loops). So, the following code didn’t work in the past:

fn main() {
    let my_cities = ["Beirut", "Tel Aviv", "Nicosia"];
 
    for city in my_cities {
        println!("{}", city);
    }
}

The compiler used to give the following message:

20.1.2 Destructuring and mapping arrays

20.1.3 Using from_fn to make arrays

20.2 char

20.3 Integers