1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
// `type Item = ..;` inside an `impl` binds a name the same block's signatures
// use as `Self::Item`. A `const` in an `impl` becomes a module-level constant
// named for both, since Nim has no per-type constant namespace.
struct Grid {
cells: Vec<i32>,
width: usize,
}
trait Cells {
type Out;
fn get_at(&self, i: usize) -> Self::Out;
fn total(&self) -> Self::Out;
}
impl Cells for Grid {
type Out = i32;
fn get_at(&self, i: usize) -> Self::Out {
self.cells[i]
}
fn total(&self) -> Self::Out {
let mut t: i32 = 0;
for c in self.cells.iter() {
t += c;
}
t
}
}
impl Grid {
const BORDER: i32 = 7;
fn at(&self, r: usize, c: usize) -> i32 {
self.cells[r * self.width + c]
}
}
fn main() {
let g = Grid {
cells: vec![1, 2, 3, 4, 5, 6],
width: 3,
};
println!("{} {}", g.get_at(0), g.get_at(5));
println!("{}", g.total());
println!("{} {}", g.at(0, 2), g.at(1, 0));
println!("{}", Grid::BORDER);
}
|