Skip to content

Commit 7232d91

Browse files
authored
Update opaque-types-type-alias-impl-trait.md
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
1 parent 60d52c8 commit 7232d91

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/opaque-types-type-alias-impl-trait.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ type Foo = impl Bar;
1212

1313
This declares an opaque type named `Foo`, of which the only information is that
1414
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).
1616

1717
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
1919
by using the opaque type in a "defining use site".
2020

2121
```rust,ignore
@@ -28,6 +28,27 @@ fn foo() -> Foo {
2828

2929
Any other "defining use site" needs to produce the exact same type.
3030

31+
Note that defining a type alias to an opaque type is an unstable feature.
32+
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.
33+
Complete example:
34+
35+
```rust
36+
#![feature(type_alias_impl_trait)]
37+
38+
trait Bar { /* stuff */ }
39+
40+
type Foo = impl Bar;
41+
42+
struct Struct;
43+
44+
impl Bar for Struct { /* stuff */ }
45+
46+
#[define_opaque(Foo)]
47+
fn foo() -> Foo {
48+
Struct
49+
}
50+
```
51+
3152
## Defining use site(s)
3253

3354
Currently only the return value of a function can be a defining use site

0 commit comments

Comments
 (0)