16 Const, “unsafe” Rust, and external crates

 

This chapter covers

  • Const generics, or generics over const values
  • Const functions that you can always call at compile time
  • Mutable statics, the unsafe way to change static variables
  • Unsafe Rust
  • External crates, including rand

It’s now time to learn about Rust’s third generic type (const generics) and all the other things to do with const and static in Rust. Const generics let you be generic over const values, which is most useful when working with arrays. Const functions are similar to regular functions, but they can be called at compile time before your program starts. We will also start to learn about the unsafe side of Rust, starting with static mut, a static that is unsafe to use. We’ll also learn about why unsafe Rust even exists and why you might never even need to touch it. Then we will start moving into external crates, which, thanks to Cargo, are extremely easy to use.

16.1 Const generics

Up to now, we have learned two types of generic parameters in Rust:

  • Generic over types—These are the generics we are most familiar with, as we learned them back in chapter 5. A generic T: Debug means any type that implements the Debug trait. When Rust users say generics, they are usually talking about type generics.
  • Generic over lifetimes—Lifetimes are actually another sort of generics. For example, when you have a 'static lifetime in a function, it means any type that has a 'static lifetime. We began learning about lifetimes in chapter 10.

16.2 Const functions

16.3 Mutable statics

16.4 Unsafe Rust

16.4.1 Overview of unsafe Rust

16.4.2 Using static mut in unsafe Rust

16.4.3 Rust’s most famous unsafe method