Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 31613b1

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
1 parent 60d52c8 commit 31613b1

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

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

Lines changed: 24 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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /