Rust Lang

Rust Const Constants

A constant is a variable that cannot be changed after the assignment. They are a universal feature across programming languages and allow us to define “static” values.

Constant values are mainly useful when you need to define a variable that does need to be changed by other parts of the program. Unlike immutable variables, constant variables in Rust cannot be made mutable even using the mut keyword.

Rust Constants

There are two types of constants in Rust:

  1. Global constants – These are unchangeable values that all program parts can use globally.
  2. Static constants – These constants are mutable but contain a static lifetime. The static lifetime is inferred automatically and does not need to be annotated.

We will not concern ourselves with static constants for this tutorial.

Rust Declare Constant Variable

To declare a constant variable in rust, we use the const keyword followed by the name of the variable and its type.

The syntax is as shown:

const var_name: type = value;

Note that you must explicitly specify the type of a constant variable, unlike normal variables in Rust.

According to the Rust rules of naming, a constant variable should have a screaming snake casing as:

const VARIABLE_NAME = value;

The example below shows how to define a constant variable called PI.

const PI: f64 = 3.1415926535;
fnmain() {
    let radius = 7.141;
println!("Area of the cirlce: {} cm2", PI*radius*radius);
}

Once declared, we can use the constant variable in any part of the program.

Area of the cirlce: 160.20200192305325 cm2

Note that the compiler will return an error if we attempt to change the value of a constant variable. An example is as shown below:

const PI: f64 = 3.1415926535;
fnmain() {
    PI = 3.141;
    let radius = 7.141;
println!("Area of the cirlce: {} cm2", PI*radius*radius);
}

The code above should return an error as we try to modify the value of a constant variable.

Conclusion

In this article, we covered how to create and use constant variables. Consts are very useful for setting global variables that would result in unexpected behavior if changed.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list