| Add generics; transpile the part of cosmic-theme that is reachable ff34e1b nandithebull 10h ago | 1 | // 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)] |
| 7 | struct Pair<T> { |
| 8 | a: T, |
| 9 | b: T, |
| 10 | } |
| 11 | |
| 12 | enum Holder<T> { |
| 13 | Empty, |
| 14 | One(T), |
| 15 | } |
| 16 | |
| 17 | impl<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 | |
| 26 | fn 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 | |
| 36 | fn count<T>(h: &Holder<T>) -> i32 { |
| 37 | match h { |
| 38 | Holder::Empty => 0, |
| 39 | Holder::One(_) => 1, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn 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 | } |