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.

Lower argument-position `impl Trait`; it was a generic parameter all along 4e4d09d · on 4e4d09dcdd22d17ba510de5639fc3a952ac73f6e · nandithebull · 6h ago
040-impl-trait-args.rs · 57 lines · 1.2 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
// `impl Trait` in argument position *is* a generic parameter -- that is Rust's
// own desugaring, `fn f(x: impl T)` for `fn f<A: T>(x: A)`. The bound is
// dropped like any other bound, so what is left is a fresh parameter, and Nim
// instantiates it structurally at the call site.
//
// In return position it is an opaque type instead: the caller cannot name it,
// and there is no Nim equivalent, so that is still rejected.

use core::fmt::Debug;

trait Area {
    fn area(&self) -> i32;
}

struct Sq {
    side: i32,
}
struct Rect {
    w: i32,
    h: i32,
}

impl Area for Sq {
    fn area(&self) -> i32 {
        self.side * self.side
    }
}
impl Area for Rect {
    fn area(&self) -> i32 {
        self.w * self.h
    }
}

fn describe(shape: impl Area) -> i32 {
    shape.area()
}

fn twice(shape: impl Area) -> i32 {
    shape.area() * 2
}

fn both(a: impl Area, b: impl Area) -> i32 {
    a.area() + b.area()
}

fn show(x: impl Debug) -> i32 {
    let _ = x;
    1
}

fn main() {
    println!("{}", describe(Sq { side: 4 }));
    println!("{}", describe(Rect { w: 3, h: 5 }));
    println!("{}", twice(Sq { side: 3 }));
    println!("{}", both(Sq { side: 2 }, Rect { w: 10, h: 10 }));
    println!("{}", show(7i32));
}