Constants in Rust

Our example discusses the support for constants. Here’s the full source code translated.

fn main() {
    const S: &str = "constant";
    println!("{}", S);

    const N: i64 = 500000000;
    println!("{}", N);

    const D: f64 = 3e20 / N as f64;
    println!("{}", D);
    
    println!("{}", D as i64);
    
    println!("{}", (N as f64).sin());
}

A const declares a constant value. In Rust, constants are declared using the const keyword followed by the name, type, and value of the constant.

To run the program, put the code in a file, for example, main.rs, and use rustc to compile it.

$ rustc main.rs
$ ./main
constant
500000000
6e+11
600000000000
-0.28470407323754404