Skip to content

Rust lang

Hello rust

1
println!("Hi");

Resources for learning rust lang

  • Rustlings
  • Exercism
  • Reading books

Random Rust

1
#[derive(PartialEq, Eq, Debug)]
2
pub enum Direction {
3
North,
4
East,
5
South,
6
West,
7
}
8
9
pub struct Robot {
10
x: i32,
11
y: i32,
12
direction: Direction,
13
}
14
15
use Direction::*;
16
17
impl Robot {
18
pub fn new(x: i32, y: i32, direction: Direction) -> Self {
19
Robot { x, y, direction }
20
}
21
22
#[must_use]
23
pub fn turn_right(self) -> Robot {
24
Robot {
25
direction: match self.direction {
26
North => East,
27
East => South,
28
South => West,
29
West => North,
30
},
31
..self
32
}
33
}
34
35
#[must_use]
36
pub fn turn_left(self) -> Robot {
37
Robot {
38
direction: match self.direction() {
39
North => West,
40
East => North,
41
South => East,
42
West => South,
43
},
44
..self
45
}
46
}
47
48
#[must_use]
49
pub fn advance(self) -> Self {
50
match self.direction {
51
North => Robot {
52
y: self.y + 1,
53
..self
54
},
55
East => Robot {
56
x: self.x + 1,
57
..self
58
},
59
South => Robot {
60
y: self.y - 1,
61
..self
62
},
63
West => Robot {
64
x: self.x - 1,
65
..self
66
},
67
}
68
}
69
70
#[must_use]
71
pub fn instructions(self, instructions: &str) -> Self {
72
instructions
73
.chars()
74
.fold(self, |robot, instruction| match instruction {
75
'A' => robot.advance(),
76
'L' => robot.turn_left(),
77
'R' => robot.turn_right(),
78
_ => robot,
79
})
80
}
81
82
pub fn position(&self) -> (i32, i32) {
83
(self.x, self.y)
84
}
85
86
pub fn direction(&self) -> &Direction {
87
&self.direction
88
}
89
}