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
1. Clarify that there is a single concrete type for an opaque type
2. Clarify that defining a type alias to an opaque type is an unstable feature
3. Add complete example
4. Clarify that defining an associate type as opaque is an unstable
feature
5. Add another complete example
Copy file name to clipboardExpand all lines: src/opaque-types-type-alias-impl-trait.md
+49-2Lines changed: 49 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -12,22 +12,44 @@ type Foo = impl Bar;
12
12
13
13
This declares an opaque type named `Foo`, of which the only information is that
14
14
it implements `Bar`. Therefore, any of `Bar`'s interface can be used on a `Foo`,
15
-
but nothing else (regardless of whether it implements any other traits).
15
+
but nothing else (regardless of whether the concrete type implements any other traits).
16
16
17
17
Since there needs to be a concrete background type,
18
-
you can (as of <!-- date-check -->January 2021) express that type
18
+
you can (as of <!-- date-check -->May 2025) express that type
19
19
by using the opaque type in a "defining use site".
20
20
21
21
```rust,ignore
22
22
struct Struct;
23
23
impl Bar for Struct { /* stuff */ }
24
+
#[define_opaque(Foo)]
24
25
fn foo() -> Foo {
25
26
Struct
26
27
}
27
28
```
28
29
29
30
Any other "defining use site" needs to produce the exact same type.
30
31
32
+
Note that defining a type alias to an opaque type is an unstable feature.
33
+
To use it, you need `nightly` and the annotations `#![feature(type_alias_impl_trait)]` on the file and `#[define_opaque(Foo)]` on the method that links the opaque type to the concrete type.
34
+
Complete example:
35
+
36
+
```rust
37
+
#![feature(type_alias_impl_trait)]
38
+
39
+
traitBar { /* stuff */ }
40
+
41
+
typeFoo=implBar;
42
+
43
+
structStruct;
44
+
45
+
implBarforStruct { /* stuff */ }
46
+
47
+
#[define_opaque(Foo)]
48
+
fnfoo() ->Foo {
49
+
Struct
50
+
}
51
+
```
52
+
31
53
## Defining use site(s)
32
54
33
55
Currently only the return value of a function can be a defining use site
@@ -61,3 +83,28 @@ impl Baz for Quux {
61
83
fn foo() -> Self::Foo { ... }
62
84
}
63
85
```
86
+
87
+
For this you would also need to use `nightly` and the (different) `#![feature(impl_trait_in_assoc_type)]` annotation.
88
+
Note that you don't need a `#[define_opaque(Foo)]` on the method anymore.
0 commit comments