Featured image of post Rust Cheatsheet

Rust Cheatsheet

Rust cheatsheet

Installation

https://doc.rust-lang.org/book/ch01-01-installation.html#installation

in linux or Mac

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

in windows

visit https://www.rust-lang.org/tools/install

Create New Project

Manual

1
2
3
fn main(){
    println!("hello world!");
}

save into main.rs and run it by rustc main.rs | ./main

With Cargo

run

1
cargo new app_name

Looping

Infinite loop

use infinite loop

```rs
    let mut n = 0;
    loop {
        n += 1;
        if n == 5 {
            continue;
        }
        if n == 10 {
            break;
        }

        println!("infinite loop {}", n);
    }
```

For Loop

example:

```rs
    let nums = 1..6;
    for i in nums {
        println!("{}", i);
    }

    let animals = vec!["cat", "dog", "mouse"];
    for animal in animals.iter() {
        println!("{}", animal);
    }

    let dog = animals[1];
    println!("{}", dog);
```

note:

  • use 1..=6 if want to count 6
  • if .iter() removed, line let dog = animals[1]; will be error
  • if we want to iter index of the array, use enumerate()
    1
    2
    3
    
        for (index, animal) in animals.iter().enumerate() {
        println!("{}: {}", index, animal);
        }
    

Enum

outside main func create enum like this:

```rs
enum Direction {
    Up,
    Down,
    Left,
    Right,
}
```

to access variant in enum, we use double collon ::. Put this in the main func

```rs
let player_direction: Direction = Direction::Up;

match player_direction {
    Direction::Up => println!("Moving up"),
    Direction::Down => println!("Moving down"),
    Direction::Left => println!("Moving left"),
    Direction::Right => println!("Moving right"),
}
```

Constant

References

Ryan Levicks
dcode doc.rust-lang.org

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus