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