Install Rust
Code Block |
---|
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh |
Hello World Example
...
Using the Package Manager
Create a project using Cargo
Code Block |
---|
|
cargo new hello_cargo |
...
It has also initialized a new Git repository along with a .gitignore file. Git files won’t be generated if you run cargo new
within an existing Git repository; you can override this behavior by using cargo new --vcs=git
.
Cargo.toml
Code Block |
---|
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies] |
Building
Build and Run
Build for Release
Code Block |
---|
|
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 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 let
keyword, and the type of the value must be annotated.
...
Rust’s naming convention for constants is to use all uppercase with underscores between words.
Shadowing
You can declare a new variable with the same name as a previous variable. Rustaceans say that the first variable is shadowed by the second, which means that the second variable is what the compiler will see when you use the name of the variable.
...
Code Block |
---|
|
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6 |
Data Types
Integer Types
Length | Signed | Unsigned |
---|
8-bit | i8 | u8 |
16-bit | i16 | u16 |
32-bit | i32 | u32 |
64-bit | i64 | u64 |
128-bit | i128 | u128 |
arch | isize | usize |
Integer Literals
Number literals | Example |
---|
Decimal | 98_222 |
Hex | 0xff |
Octal | 0o77 |
Binary | 0b1111_0000 |
Byte (u8 only) | b'A' |
References