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
|
|
save into main.rs and run it by rustc main.rs | ./main
With Cargo
run
|
|
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..=6if want to count6 - if
.iter()removed, linelet dog = animals[1];will be error - if we want to iter index of the array, use
enumerate()1 2 3for (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"),
}
```