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

040-impl-trait-args.rs · 57 lines · 1.2 KBRust Blame HistoryRaw
Lower argument-position `impl Trait`; it was a generic parameter all along 4e4d09d nandithebull 9h ago1// `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
9use core::fmt::Debug;
10
11trait Area {
12 fn area(&self) -> i32;
13}
14
15struct Sq {
16 side: i32,
17}
18struct Rect {
19 w: i32,
20 h: i32,
21}
22
23impl Area for Sq {
24 fn area(&self) -> i32 {
25 self.side * self.side
26 }
27}
28impl Area for Rect {
29 fn area(&self) -> i32 {
30 self.w * self.h
31 }
32}
33
34fn describe(shape: impl Area) -> i32 {
35 shape.area()
36}
37
38fn twice(shape: impl Area) -> i32 {
39 shape.area() * 2
40}
41
42fn both(a: impl Area, b: impl Area) -> i32 {
43 a.area() + b.area()
44}
45
46fn show(x: impl Debug) -> i32 {
47 let _ = x;
48 1
49}
50
51fn 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}