nandi/rustnimpublic Fork 0
af6e50f646055dc5b291c9e602bc9ee01874f9d6
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.

030-generics.rs · 65 lines · 1.5 KBRust Blame HistoryRaw
Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 14h ago1// Rust generics map to Nim's, which are instantiated structurally at the call
2// site much as Rust's are. Trait bounds and `where` clauses are dropped: an
3// operation the bound permitted either exists for the instantiated type or is
4// a compile error at that instantiation, so dropping it cannot change what an
5// accepted program means.
6#[derive(Copy, Clone)]
7struct Pair<T> {
8 a: T,
9 b: T,
10}
11
12enum Holder<T> {
13 Empty,
14 One(T),
15}
16
17impl<T: Copy> Pair<T> {
18 fn first(&self) -> T {
19 self.a
20 }
21 fn swapped(&self) -> Pair<T> {
22 Pair { a: self.b, b: self.a }
23 }
24}
25
26fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
27 let mut m: T = xs[0];
28 for x in xs.iter() {
29 if *x > m {
30 m = *x;
31 }
32 }
33 m
34}
35
36fn count<T>(h: &Holder<T>) -> i32 {
37 match h {
38 Holder::Empty => 0,
39 Holder::One(_) => 1,
40 }
41}
42
43fn main() {
44 let p: Pair<i32> = Pair { a: 1, b: 2 };
45 let q: Pair<i32> = p.swapped();
46 println!("{} {} {}", q.a, q.b, p.first());
47
48 let f: Pair<f64> = Pair { a: 1.5, b: -0.5 };
49 println!("{} {}", f.swapped().a, f.first());
50
51 let v: Vec<i32> = vec![3, 9, 4];
52 println!("{}", largest(&v));
53 let w: Vec<f64> = vec![1.5, 0.25, 9.75];
54 println!("{}", largest(&w));
55 let b: Vec<u8> = vec![7, 200, 3];
56 println!("{}", largest(&b));
57
58 let h: Holder<i32> = Holder::One(7);
59 let e: Holder<i32> = Holder::Empty;
60 println!("{} {}", count(&h), count(&e));
61 match h {
62 Holder::Empty => println!("empty"),
63 Holder::One(v) => println!("one {}", v),
64 }
65}