nandi/rustnimpublic Fork 0
3d4a7d283b83d3a5305dfc6654c290bd4ee162ae
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

033-associated-types.rs · 49 lines · 1.0 KBRust Blame HistoryRaw
Add associated types and consts, and test whether the blocker stack bottoms out 8354895 nandithebull 12h ago1// `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
5struct Grid {
6 cells: Vec<i32>,
7 width: usize,
8}
9
10trait Cells {
11 type Out;
12 fn get_at(&self, i: usize) -> Self::Out;
13 fn total(&self) -> Self::Out;
14}
15
16impl 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
32impl 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
40fn 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}