Skip to content

Commit 5822f48

Browse files
committed
Update section on "existential type" to "opaque type"
1 parent b4b7dca commit 5822f48

File tree

2 files changed

+62
-48
lines changed

2 files changed

+62
-48
lines changed

Diff for: src/existential-types.md

-48
This file was deleted.

Diff for: src/opaque-types-type-alias-impl-trait.md

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Opaque types (type alias `impl Trait`)
2+
3+
Opaque types are syntax to declare an opaque type alias that only
4+
exposes a specific set of traits as their interface; the concrete type in the
5+
background is inferred from a certain set of use sites of the opaque type.
6+
7+
This is expressed by using `impl Trait` within type aliases, for example:
8+
9+
```rust,ignore
10+
type Foo = impl Bar;
11+
```
12+
13+
This declares an opaque type named `Foo`, of which the only information is that
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).
16+
17+
Since there needs to be a concrete background type, you can currently
18+
express that type by using the opaque type in a "defining use site".
19+
20+
```rust,ignore
21+
struct Struct;
22+
impl Bar for Struct { /* stuff */ }
23+
fn foo() -> Foo {
24+
Struct
25+
}
26+
```
27+
28+
Any other "defining use site" needs to produce the exact same type.
29+
30+
## Defining use site(s)
31+
32+
Currently only the return value of a function can be a defining use site
33+
of an opaque type (and only if the return type of that function contains
34+
the opaque type).
35+
36+
The defining use of an opaque type can be any code *within* the parent
37+
of the opaque type definition. This includes any siblings of the
38+
opaque type and all children of the siblings.
39+
40+
The initiative for *"not causing fatal brain damage to developers due to
41+
accidentally running infinite loops in their brain while trying to
42+
comprehend what the type system is doing"* has decided to disallow children
43+
of opaque types to be defining use sites.
44+
45+
### Associated opaque types
46+
47+
Associated opaque types can be defined by any other associated item
48+
on the same trait `impl` or a child of these associated items. For instance:
49+
50+
```rust,ignore
51+
trait Baz {
52+
type Foo;
53+
fn foo() -> Self::Foo;
54+
}
55+
56+
struct Quux;
57+
58+
impl Baz for Quux {
59+
type Foo = impl Bar;
60+
fn foo() -> Self::Foo { ... }
61+
}
62+
```

0 commit comments

Comments
 (0)