Skip to content

Commit 6469fba

Browse files
committed
Trait objects
1 parent efd0483 commit 6469fba

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// run-pass
2+
#![feature(const_generics_defaults)]
3+
4+
trait Trait<const N: u8 = 12> {
5+
fn uwu(&self) -> u8 {
6+
N
7+
}
8+
}
9+
10+
impl Trait for u32 {}
11+
12+
impl Trait<12> for u64 {
13+
fn uwu(&self) -> u8 {
14+
*self as u8
15+
}
16+
}
17+
18+
fn foo(arg: &dyn Trait) -> u8 {
19+
arg.uwu()
20+
}
21+
22+
trait Traitor<const N: u8 = 1, const M: u8 = N> {
23+
fn owo(&self) -> u8 {
24+
M
25+
}
26+
}
27+
28+
impl Traitor<2> for bool { }
29+
impl Traitor for u8 {
30+
fn owo(&self) -> u8 {
31+
*self
32+
}
33+
}
34+
35+
fn bar<const N: u8>(arg: &dyn Traitor<N>) -> u8 {
36+
arg.owo()
37+
}
38+
39+
fn main() {
40+
assert_eq!(foo(&10_u32), 12);
41+
assert_eq!(foo(&3_u64), 3);
42+
43+
assert_eq!(bar(&true), 2);
44+
assert_eq!(bar(&1_u8), 1);
45+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#![feature(const_generics_defaults)]
2+
3+
trait Trait<const N: u8 = 12> {
4+
fn uwu(&self) -> u8 {
5+
N
6+
}
7+
}
8+
9+
impl Trait<2> for u32 {}
10+
11+
fn foo(arg: &dyn Trait) -> u8 {
12+
arg.uwu()
13+
}
14+
15+
trait Traitor<const N: u8 = 1, const M: u8 = N> {
16+
fn owo(&self) -> u8 {
17+
M
18+
}
19+
}
20+
21+
impl Traitor<2, 3> for bool { }
22+
23+
fn bar<const N: u8>(arg: &dyn Traitor<N>) -> u8 {
24+
arg.owo()
25+
}
26+
27+
fn main() {
28+
foo(&10_u32);
29+
//~^ error: the trait bound `u32: Trait` is not satisfied
30+
bar(&true);
31+
//~^ error: the trait bound `bool: Traitor<{_: u8}, {_: u8}>` is not satisfied
32+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
error[E0277]: the trait bound `u32: Trait` is not satisfied
2+
--> $DIR/trait_objects_fail.rs:28:9
3+
|
4+
LL | foo(&10_u32);
5+
| --- ^^^^^^^ the trait `Trait` is not implemented for `u32`
6+
| |
7+
| required by a bound introduced by this call
8+
|
9+
= help: the following implementations were found:
10+
<u32 as Trait<2_u8>>
11+
= note: required for the cast to the object type `dyn Trait`
12+
13+
error[E0277]: the trait bound `bool: Traitor<{_: u8}, {_: u8}>` is not satisfied
14+
--> $DIR/trait_objects_fail.rs:30:9
15+
|
16+
LL | bar(&true);
17+
| --- ^^^^^ the trait `Traitor<{_: u8}, {_: u8}>` is not implemented for `bool`
18+
| |
19+
| required by a bound introduced by this call
20+
|
21+
= help: the following implementations were found:
22+
<bool as Traitor<2_u8, 3_u8>>
23+
= note: required for the cast to the object type `dyn Traitor<{_: u8}, {_: u8}>`
24+
25+
error: aborting due to 2 previous errors
26+
27+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)