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.

Add generics; transpile the part of cosmic-theme that is reachable ff34e1b · on 3d4a7d283b83d3a5305dfc6654c290bd4ee162ae · nandithebull · 9h ago
030-generics.rs · 65 lines · 1.5 KBRust Blame HistoryRaw
 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Rust generics map to Nim's, which are instantiated structurally at the call
// site much as Rust's are. Trait bounds and `where` clauses are dropped: an
// operation the bound permitted either exists for the instantiated type or is
// a compile error at that instantiation, so dropping it cannot change what an
// accepted program means.
#[derive(Copy, Clone)]
struct Pair<T> {
    a: T,
    b: T,
}

enum Holder<T> {
    Empty,
    One(T),
}

impl<T: Copy> Pair<T> {
    fn first(&self) -> T {
        self.a
    }
    fn swapped(&self) -> Pair<T> {
        Pair { a: self.b, b: self.a }
    }
}

fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
    let mut m: T = xs[0];
    for x in xs.iter() {
        if *x > m {
            m = *x;
        }
    }
    m
}

fn count<T>(h: &Holder<T>) -> i32 {
    match h {
        Holder::Empty => 0,
        Holder::One(_) => 1,
    }
}

fn main() {
    let p: Pair<i32> = Pair { a: 1, b: 2 };
    let q: Pair<i32> = p.swapped();
    println!("{} {} {}", q.a, q.b, p.first());

    let f: Pair<f64> = Pair { a: 1.5, b: -0.5 };
    println!("{} {}", f.swapped().a, f.first());

    let v: Vec<i32> = vec![3, 9, 4];
    println!("{}", largest(&v));
    let w: Vec<f64> = vec![1.5, 0.25, 9.75];
    println!("{}", largest(&w));
    let b: Vec<u8> = vec![7, 200, 3];
    println!("{}", largest(&b));

    let h: Holder<i32> = Holder::One(7);
    let e: Holder<i32> = Holder::Empty;
    println!("{} {}", count(&h), count(&e));
    match h {
        Holder::Empty => println!("empty"),
        Holder::One(v) => println!("one {}", v),
    }
}