Getting Started with Rust
This guide will help you write your first Rust program.
Installation
Install Rust using rustup:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Verify the installation:
rustc --version
cargo --version
Hello World
Create a new file called main.rs:
fn main() {
println!("Hello, world!");
}
Compile and run:
rustc main.rs
./main
Using Cargo
Create a new project with cargo new:
cargo new hello_cargo
cd hello_cargo
This creates the following structure:
hello_cargo/
├── Cargo.toml
└── src/
└── main.rs
The Cargo.toml contains project metadata:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
Variables and Types
Rust has strong static typing:
fn main() {
// Immutable by default
let x = 5;
// Mutable variables need `mut`
let mut y = 10;
y = 20;
// Type annotations
let z: i32 = 30;
// Strings
let s1 = "hello"; // &str
let s2 = String::from("world"); // String
// Arrays and vectors
let arr: [i32; 3] = [1, 2, 3];
let vec: Vec<i32> = vec![1, 2, 3];
}
Functions
Functions use the fn keyword:
fn add(a: i32, b: i32) -> i32 {
a + b // No semicolon = return value
}
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
let result = add(5, 3);
println!("5 + 3 = {}", result);
greet("Rust");
}
Error Handling
Rust uses Result and Option for error handling:
use std::fs::File;
use std::io::{self, Read};
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn main() {
match read_file("hello.txt") {
Ok(contents) => println!("{}", contents),
Err(e) => eprintln!("Error: {}", e),
}
}
Inline Code Examples
Use println! to print to stdout. The ! indicates a macro.
Variables are immutable by default. Use let mut x = 5; for mutability.
The ? operator propagates errors. It's equivalent to:
match result {
Ok(val) => val,
Err(e) => return Err(e),
}