Primitive Types
- bool: Boolean type (
true
orfalse
).
let is_active: bool = true;
- char: Represents a single Unicode scalar value.
let letter: char = 'a';
- f32, f64: 32-bit and 64-bit floating point types.
let pi: f64 = 3.1415;
- i8, i16, i32, i64, i128, isize: Signed integers.
let age: i32 = 30;
- u8, u16, u32, u64, u128, usize: Unsigned integers.
let count: u32 = 100;
- str: String slices.
let greeting: &str = "Hello, world!";
- slice: Contiguous sequences of elements.
let numbers: &[i32] = &[1, 2, 3];
- array: Fixed-size sequences of elements.
let arr: [i32; 3] = [1, 2, 3];
- tuple: Heterogeneous lists of fixed size.
let person: (&str, i32) = ("Alice", 30);
- unit: The empty tuple
()
.
let unit: () = ();
Key Modules
- alloc: Memory allocation APIs.
use alloc::vec::Vec;
let mut vec = Vec::new();
vec.push(1);
- collections: Common data structures like
Vec
,HashMap
.
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("key", "value");
- io: Input/output functionalities, e.g.,
Read
,Write
.
use std::io::Write;
let mut buffer = Vec::new();
buffer.write_all(b"hello").unwrap();
- fs: Filesystem operations.
use std::fs;
let contents = fs::read_to_string("file.txt").unwrap();
- net: Networking primitives like TCP/UDP.
use std::net::TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
- sync: Synchronization primitives like
Mutex
,Arc
.
use std::sync::{Arc, Mutex};
let data = Arc::new(Mutex::new(5));
- thread: Threading abstractions and operations.
use std::thread;
thread::spawn(|| {
println!("Hello from a thread!");
}).join().unwrap();
Macros
- assert, assert_eq, assert_ne: Assertion macros for testing conditions.
assert!(1 == 1);
assert_eq!(2 + 2, 4);
assert_ne!(3, 4);
- panic: Macro to cause a panic.
panic!("This is a panic!");
- print, println: Macros for printing to standard output.
println!("Hello, world!");
- format: Create formatted strings.
let formatted = format!("Hello, {}!", "world");
- include_str, include_bytes: Include file contents as a string or bytes.
let content: &str = include_str!("file.txt");
Error Handling
- Option: Represents an optional value.
let some_value: Option<i32> = Some(10);
let no_value: Option<i32> = None;
- Result: Represents either success (
Ok
) or failure (Err
).
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(a / b)
}
}
Iteration
- Iterator: Trait for iteration.
let nums = vec![1, 2, 3];
let sum: i32 = nums.iter().sum();
- for: Loop construct for iterating over collections.
let nums = vec![1, 2, 3];
for num in nums {
println!("{}", num);
}
For more details, visit the Rust Standard Library documentation.