This tutorial provides a basic introduction to Rust programming language. We'll cover essential concepts and basic syntax.
- Create a new Rust project:
cargo new rust-hello-world
cd rust-hello-world- Common Cargo Commands:
cargo check: Check code for errors without buildingcargo build: Compile the projectcargo run: Build and run the projectcargo test: Run testscargo doc: Generate documentation
- By default, variables are immutable in Rust
- Use
mutkeyword to make variables mutable:
let x = 5; // immutable
let mut y = 5; // mutable-
Integer Types
- Default is i32 (32-bit)
- Signed: i8, i16, i32, i64, i128
- Unsigned: u8, u16, u32, u64, u128
-
Floating-Point Types
- Default is f64 (64-bit)
- Types: f32, f64
-
Boolean Type
- Values: true, false
- Size: 1 byte
-
Character Type
- Unicode scalar value
- 4 bytes (32-bit)
- Supports emoji and international characters
-
Compound Types
- Tuples: Fixed-length collection of values of different types
let tup: (i32, f64, bool) = (500, 6.4, true);
- Arrays: Fixed-length collection of same type
let arr: [i32; 5] = [1, 2, 3, 4, 5];
fn function_name(parameter: Type) -> ReturnType {
// function body
}One of Rust's most unique features:
- Each value has a single owner
- Only one owner at a time
- Value is dropped when owner goes out of scope
- Prevents memory leaks and ensures memory safety
Example:
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2, s1 is no longer validFor simple types (integers, booleans, etc.), Rust automatically makes copies instead of moving ownership. These types implement the Copy trait.
Structs: Custom data types to group related data
struct User {
username: String,
email: String,
active: bool,
}Enums: Type that can be one of several variants
enum IpAddrKind {
V4,
V6,
}- Error handling with Result and Option
- Pattern matching with match expressions
- Collections (Vec, HashMap)
- Modules and packages
- Traits and generics