Skip to main content
czerasz.com: notes
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Rust

Basic

Run code in example.rs:

cargo run -q -bin example

Elements of Rust – Core Types and Traits

Visit a clickable visual guide to the Rust type system here.

Standard Library

HashMap

Data is sotred in random order.

use std::collection::HashMap;

for (person, age) in people.iter() {}
for person in people.keys() {}
for age in people.values() {}

Function on Structs

struct Person {
    name: Person,
}

impl Person {
    fn new() -> Result<Self, &str> {
        ...
    }

    fn process(&self) {
        self.name;
    }
}

## Result

```rust
enum Resul<T, E> {
    Ok(T),
    Err(E),
}

Basic example:

fn main() {
    let example = example();
    match example {
       Ok(v) => println!("ok: {:?}", v),
       Err(e) => println!("error: {:?}", e),
    }
}

Return nothing:

fn some_thing() -> Result<(), String> {
    ...
    Ok(())
}

With ? we can chain errors:

let some = somple()?;

? will behave like a match and if Err occurs then it automatically returns.

Documentation

View Rust documentation locally:

rustup doc

View documentation for the cureent project:

cargo doc --open

To use automatic documentation in rust use /// like in the example below:

/// Some example Color enum.
enum Color {
    Red,
    Blue,
}