Skip to content

Commit 489c271

Browse files
committed
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 4. Clarify that defining an associate type as opaque is an unstable feature 5. Add another complete example
1 parent 60d52c8 commit 489c271

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

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

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,44 @@ 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
2222
struct Struct;
2323
impl Bar for Struct { /* stuff */ }
24+
#[define_opaque(Foo)]
2425
fn foo() -> Foo {
2526
Struct
2627
}
2728
```
2829

2930
Any other "defining use site" needs to produce the exact same type.
3031

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+
trait Bar { /* stuff */ }
40+
41+
type Foo = impl Bar;
42+
43+
struct Struct;
44+
45+
impl Bar for Struct { /* stuff */ }
46+
47+
#[define_opaque(Foo)]
48+
fn foo() -> Foo {
49+
Struct
50+
}
51+
```
52+
3153
## Defining use site(s)
3254

3355
Currently only the return value of a function can be a defining use site
@@ -61,3 +83,28 @@ impl Baz for Quux {
6183
fn foo() -> Self::Foo { ... }
6284
}
6385
```
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.
89+
Complete example:
90+
91+
```
92+
#![feature(impl_trait_in_assoc_type)]
93+
94+
trait Bar {}
95+
struct Zap;
96+
97+
impl Bar for Zap {}
98+
99+
trait Baz {
100+
type Foo;
101+
fn foo() -> Self::Foo;
102+
}
103+
104+
struct Quux;
105+
106+
impl Baz for Quux {
107+
type Foo = impl Bar;
108+
fn foo() -> Self::Foo { Zap }
109+
}
110+
```

0 commit comments

Comments
 (0)