kuniga.me > Docs > Rust Cheatsheet
bool
char
i8
, i16
, i32
, i64
- signed intu8
, u16
, u32
, u64
- unsigned intf32
, f64
- float point typeArrays are of fixed size. For variable size, see Vec
.
// Initialize array
let arr: [i32; 3] = [1, 2, 3];
let arr: [i32; 10] = [0; 10];
let arr: [i32; 3] = [1, 2, 3];
for x in &arr {
print!("{} ", x);
}
bool
true
, false
optional<T>
// Handle option:
match my_option {
Some(value) => value,
None => 1, // handle null value
}
// Create Some
Some(1)
// Throw if None
my_option.unwrap()
// Test if some
my_option.is_some()
// Test if none
my_option.is_none()
String
- string object&str
- string slice&'static str
- string literallet concatenated = format!("{}{}", a, b);
or
let s = "hello".to_owned();
let t = " world".to_owned();
s. push_str(&t);
keywords: record / object / shape
struct Tree {
guess: Vec<i32>,
children: Vec<Tree>,
}
let foo = Foo { x: (1, 2), y: 3 };
let Foo { x: (a, b), y } = foo;
struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.length * self.width
}
}
let tup: (i32, String) = (64, "hello")
// Can be accessed in the . notation
tup.0 // 64
tup.1 // "hello"
fn myFun(arg1: i32, arg2: i32) -> i32 {
}
Rust doesn’t support default arguments
keywords: lambda
let plus_one = |x: i32| x + 1;
let multi_line = |x: i32| {
let mut result: i32 = x;
result += 1;
result
}
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero", n);
}
for i in 0..3 {
println!("{}", i);
}
See also “Iterating” on different data structures.
!
is the Rust version of ~
let mut vec = Vec::new();
vec.push(1);
for item in vec.iter() {
...
}
let u = vec![1, 2, 3];
let v: Vec<_> = u.iter().map(f).collect();
let u = vec![1, 2, 3];
let v: Vec<_> = u.iter().filter(f).collect();
In-place
let mut u = vec![1, 2, 3];
u.retain(f);
vec.len()
Reference: HashMap
use std::collections::HashMap;
// Type definition
HashMap<String, String>;
// Create New
my_map = HashMap::new()
// Insert
my_map.insert(
"key_a".to_string(),
"value_a".to_string(),
);
// Access
match my_map.get("key_a") {
Some(value) => println!("value={}", value),
None => println!("not found")
}
// All values
for value in my_map.values() {
}
// All keys
for key in my_map.keys() {
}
// Empty string
let mut my_str: String = "".to_owned();
// Other form
let mut my_str = String::from("Hello");
// Length
my_str.len();
// Iterate over its characters
for c in my_str.chars() {
// do something with c
}
pub structure MyClass {
my_field: bool,
}
impl MyClass {
// Constructor-like
pub fn new() -> MyClass {
return MyClass {
my_field: true,
}
}
// Read Method
pub fn set(&self, value: bool) {
self.my_field = value;
}
// Write Method
pub fn set(&mut self, value: bool) {
self.my_field = value;
}
}