21 Continuing the tour

 

This chapter covers

  • The mem module
  • The std library prelude
  • Setting panic hooks and viewing backtraces
  • Other macros

This is the second of two chapters touring the standard library, with a lot of new (but not difficult) types that you’ll find useful to know. Near the end, we will look at some macros we haven’t encountered before, which will lead into the next chapter, where you will learn how to write your own!

21.1 std::mem

As the name implies, the std::mem module has types and functions for dealing with memory. The functions inside this module are particularly interesting (and convenient). We have seen some of them already, such as size_of(), size_of_val(), and drop():

use std::mem;
 
fn main() {
    println!("Size of an i32: {}", mem::size_of::<i32>());
    let my_array = [8; 50];
    println!("Size of this array: {}", mem::size_of_val(&my_array));
    let some_string = String::from("Droppable because it's not Copy");
    drop(some_string);
    // some_string.clear();     #1
}

This prints

Size of an i32: 4
Size of this array: 200

Note that in the previous code we didn’t need to write mem::drop(), just drop(), because this function is part of the prelude. We will look at the prelude shortly.

Technically, you can call drop() on a Copy type, but it will have no effect. As the function documentation states:

21.2 Setting panic hooks

21.3 Viewing backtraces

21.4 The standard library prelude