Rust Introduction
Rust is a fast, safe programming language for building reliable software.
What is Rust?
- Rust started at Mozilla and version 1.0 was released in 2015
- It is a compiled language: code becomes a fast program file
- It has no garbage collector, yet it manages memory safely
- It is now used by Microsoft, Amazon, Google, Cloudflare and many others
Where is Rust Used?
| Area | Example |
|---|---|
| Systems | Parts of Windows, Linux and Android |
| Web | Fast backend servers and WebAssembly |
| Tools | Command-line tools like ripgrep |
| Embedded | Programs for small devices |
Installing Rust
- Visit rust-lang.org and follow the steps to install rustup.
- Open a new terminal and check the version:
Example
bash
rustc --version
cargo --versionrustc is the compiler. Cargo is Rust's build tool and package manager. You will use Cargo almost all the time.
Do not want to install anything yet? Use the Rust Playground in your browser at play.rust-lang.org.
Creating a Project with Cargo
Example
bash
cargo new hello
cd hello
cargo runcargo new creates a folder with a Cargo.toml file (project settings) and src/main.rs (your code). cargo run builds and runs the program.
Your First Program
Open src/main.rs:
Example
rust
fn main() {
println!("Hello, Workownix!");
}Output
Hello, Workownix!
The example explained
| Code | Meaning |
|---|---|
fn | Declares a function |
main | The function where every Rust program starts |
println! | A macro that prints a line. The ! means it is a macro, not a normal function |
; | Ends a statement. Rust needs semicolons |
Printing Values
Use {} as a placeholder inside the text. Values fill the placeholders in order. You can also write a variable's name inside the braces.
Example
rust
fn main() {
let name = "Ayesha";
let age = 21;
println!("{} is {} years old", name, age);
println!("{name} studies at Workownix");
print!("Same ");
print!("line\n");
println!("{:?}", (1, 2, 3));
}Output
Ayesha is 21 years old Ayesha studies at Workownix Same line (1, 2, 3)
print!does not add a new line.{:?}is the debug format, useful for printing tuples, arrays and other groups of values.
Comments
Example
rust
// A line comment
/* A block comment */
/// A documentation comment, used above functionsExercise
Exercise
What does the ! in println! mean?
