You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Emulate dynamic dispatch and ["sealed classes"](https://kotlinlang.org/docs/reference/sealed-classes.html) using a proxy enum, which defers all method calls to its variants.
4
6
@@ -7,7 +9,7 @@ In rust, dynamic dispatch is done using trait objects (`dyn Trait`).
7
9
They enable us to have runtime polymorphism, a way of expressing that a type implements a
8
10
certain trait while ignoring its concrete implementation.
9
11
10
-
```
12
+
```rust
11
13
letanimal:&dynAnimal=random_animal();
12
14
animal.feed(); // may print "mew", "growl" or "squeak"
13
15
```
@@ -18,7 +20,7 @@ getting a concrete implementation back from a trait object (downcasting) is pain
18
20
19
21
If you know there are only a finite number of implentations to work with, an `enum` might be
20
22
better at expressing such a relationship:
21
-
```
23
+
```rust
22
24
enumAnimal {
23
25
Cat(Cat),
24
26
Lion(Lion),
@@ -38,7 +40,7 @@ Rust, however, does *not*.
38
40
`proxy-enum` simplifies working with such types using procedural macros.
39
41
40
42
## Usage
41
-
```
43
+
```rust
42
44
#[proxy_enum::proxy(Animal)]
43
45
modproxy {
44
46
enumAnimal {
@@ -54,7 +56,7 @@ mod proxy {
54
56
}
55
57
```
56
58
This will expand to:
57
-
```
59
+
```rust
58
60
modproxy {
59
61
enumAnimal {
60
62
Cat(Cat),
@@ -75,7 +77,7 @@ mod proxy {
75
77
```
76
78
This, however, will only compile if `Cat`, `Lion` and `Mouse` all have a method called `feed`.
77
79
Since rust has traits to express common functionality, trait implentations can be generated too:
78
-
```
80
+
```rust
79
81
#[proxy_enum::proxy(Animal)]
80
82
modproxy {
81
83
enumAnimal {
@@ -95,7 +97,7 @@ mod proxy {
95
97
Since the macro has to know which methods the trait contains, it has to be defined within the
96
98
module. However, implementations for external traits can be generated too:
0 commit comments