Rust Tutorials: Constants (`const`)

beginner
12 min

Rust Tutorials: Constants (const)

Welcome to our deep dive into Rust's world of constants! In this lesson, we'll learn about const in Rust, a powerful tool to define and use constants in your projects.

Let's start with the basics 🎯:

What are Constants in Rust?

Just like in other programming languages, constants in Rust are immutable values that we can use throughout our code. Constants are declared with the const keyword followed by a name and an initial value.

Here's a simple example:

rust
const MY_FAVORITE_COLOR: &str = "Blue";

In this example, MY_FAVORITE_COLOR is a constant with the value "Blue". 💡 Pro Tip: Constants are always implicitly marked as immutable in Rust, meaning they cannot be reassigned once defined.

Understanding Types in Constants

Like variables, constants also have types in Rust. The type of a constant is inferred based on the initial value you provide.

For instance, let's create a constant PI with a floating-point value:

rust
const PI: f64 = 3.14159265358979323846;

Here, the type of the constant PI is f64, a floating-point number with 6 decimal places of precision.

Using Constants in Your Code

Using constants in Rust is quite straightforward. You can access a constant like any other variable in your code:

rust
fn main() { println!("My favorite color is: {}", MY_FAVORITE_COLOR); println!("PI value is: {}", PI); }

When you run this code, you'll see the output as:

My favorite color is: Blue PI value is: 3.141593

Now, let's test your understanding with a quiz 📝:

Quick Quiz
Question 1 of 1

What's the type of the constant `PI` in the following code?

Stay tuned for our next lesson, where we'll delve deeper into constants in Rust, exploring advanced usage and best practices! ✅