| Lower argument-position `impl Trait`; it was a generic parameter all along 4e4d09d nandithebull 9h ago | 1 | // `impl Trait` in argument position *is* a generic parameter -- that is Rust's |
| 2 | // own desugaring, `fn f(x: impl T)` for `fn f<A: T>(x: A)`. The bound is |
| 3 | // dropped like any other bound, so what is left is a fresh parameter, and Nim |
| 4 | // instantiates it structurally at the call site. |
| 5 | // |
| 6 | // In return position it is an opaque type instead: the caller cannot name it, |
| 7 | // and there is no Nim equivalent, so that is still rejected. |
| 8 | |
| 9 | use core::fmt::Debug; |
| 10 | |
| 11 | trait Area { |
| 12 | fn area(&self) -> i32; |
| 13 | } |
| 14 | |
| 15 | struct Sq { |
| 16 | side: i32, |
| 17 | } |
| 18 | struct Rect { |
| 19 | w: i32, |
| 20 | h: i32, |
| 21 | } |
| 22 | |
| 23 | impl Area for Sq { |
| 24 | fn area(&self) -> i32 { |
| 25 | self.side * self.side |
| 26 | } |
| 27 | } |
| 28 | impl Area for Rect { |
| 29 | fn area(&self) -> i32 { |
| 30 | self.w * self.h |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn describe(shape: impl Area) -> i32 { |
| 35 | shape.area() |
| 36 | } |
| 37 | |
| 38 | fn twice(shape: impl Area) -> i32 { |
| 39 | shape.area() * 2 |
| 40 | } |
| 41 | |
| 42 | fn both(a: impl Area, b: impl Area) -> i32 { |
| 43 | a.area() + b.area() |
| 44 | } |
| 45 | |
| 46 | fn show(x: impl Debug) -> i32 { |
| 47 | let _ = x; |
| 48 | 1 |
| 49 | } |
| 50 | |
| 51 | fn main() { |
| 52 | println!("{}", describe(Sq { side: 4 })); |
| 53 | println!("{}", describe(Rect { w: 3, h: 5 })); |
| 54 | println!("{}", twice(Sq { side: 3 })); |
| 55 | println!("{}", both(Sq { side: 2 }, Rect { w: 10, h: 10 })); |
| 56 | println!("{}", show(7i32)); |
| 57 | } |