Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
themeEmacs
cargo build --release

This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run cargo build --release and benchmark with the executable in target/release.


Variables

Immutable/Mutable

Variables by default are immutable, meaning they can't be changed once set.

Code Block
fn main() {
    let x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}

The above code would generate an error since we are trying to overwrite the value of x.


We can make the variable mutable by adding mut the initial assignment:

Code Block
fn main() {
    let mut x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}

The above code compiles.


Constants

You declare constants using the const keyword instead of the letkeyword, and the type of the value must be annotated.

Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of code need to know about.

Code Block
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; 
const PI: f32 = 3.14;

Rust’s naming convention for constants is to use all uppercase with underscores between words.




References

ReferenceURL
The Rust Programming Languagehttps://doc.rust-lang.org/book/title-page.html