O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Constants and statics

Rust allows defining global values that are visible everywhere in your program. However, since global variables are a breeding ground for the nastiest bugs out there, there are some safety mechanisms. Immutable globals are fine, but mutable globals need be used inside unsafe blocks. Before looking at the dangerous parts, let's first see how the immutable globals work.

The first form of global values is constants. These are good for giving descriptive names for your literal values that do not need to change during the lifetime of a program. As you might remember from before, Rust has local type inference, but not global. This means that the types of constants need to be written manually. Here's how the syntax is:

 const ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required