Resources (books, tutorials, etc.)

A half-hour to learn Rust - blog post, a great intro into the language. It may be enough to start reading the code, but not enough for writing.

Easy Rust — a book about rust

Many companies and people now learn Rust, and they could learn faster with a book that has easy English. This textbook is for these companies and people to learn Rust with simple English.

The Rust Programming Language — “Rust book”. It’s a standard choice for those who want to start with Rust. A bit difficult to read sometimes.

The Rust Standard Library — documentation of the standard library.

Rust by Example — “Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust concepts and standard libraries”

Rust code snippets

String basics

// Statically allocated string slice
let hello = "Hello";

// Equivalent to the previous one, a bit more verbose
let hello_again: &'static str = "Hello";

// create a mutable empty String
let mut s = String::new();

// A mutable empty String with a pre-allocated buffer
let mut s_with_capacity = String::with_capacity(10);

// Add a string slice to a String
s.push_str("foo");

// Convert from a string slice to a String
let foo = "foo".to_string();
// another way
let bar = String::from("bar");

// Coerce a String into &str with &
let baz: &str = &bar;

Length of strings

fn main() {
    let s = String::from("hello🤦‍♂️");
    println!("length of '{}' is {}", s, s.len());
    let s = String::from("hello🤦");
    println!("length of '{}' is {}", s, s.len());
    let s = String::from("hello");
    println!("length of '{}' is {}", s, s.len());
}

prints

length of 'hello🤦‍♂️' is 18
length of 'hello🤦' is 9
length of 'hello' is 5

Iterate over all the prefixes of a String:

for (i, _) in s.chars().enumerate() {
    let prefix = &s[..i+1];
}

playground

Iteration

fn main() {
    let a = [1, 2, 3];

    // forward
    for x in a.iter() {
        print!("{} ", x);
    }
    
    // backward
    for x in a.iter().rev() {
        print!("{} ", x);
    }
}

playground

Hashmap

Counting strings using a Hashmap:

let mut counter: HashMap<String, usize> = HashMap::new();
// s is a str to add
match counter.get_mut(s) {
    Some(x) => {
        *x += 1;
    }
    None => {
        counter.insert(s.to_string(), 1);
    }
}

More info:

Testing

fn f(x: i32) -> i32 {
    x * 2
}

fn f_unwrap(x: Option<i32>) -> i32 {
    x.unwrap()
}

// The module is only built when testing
#[cfg(test)]
mod test {
    // loading functions from the parent space
    use super::f;
    use super::f_unwrap;
    
    // actual test
    #[test]
    fn test_f() {
        assert_eq!(f(12), 24);
    }
    
    // another test
    #[test]
    fn test_f_unwrap_ok() {
        f_unwrap(Some(12));
    }
    
    // verify that function panics
    #[test]
    #[should_panic]
    fn test_f_unwrap_must_fail() {
        f_unwrap(None);
    }
}

playground