Skip to content

Commit adcdbf0

Browse files
committed
Explicitly prohibit type parameters as named types of unnamed fields
1 parent 2ceb8e7 commit adcdbf0

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

text/0000-unnamed-fields.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,49 @@ struct S {
411411

412412
The error will identify the duplicate `a` fields as the sources of the error.
413413

414+
## Generics and type parameters
415+
416+
You can use this feature with a struct or union that has a generic type:
417+
418+
```rust
419+
#[repr(C)]
420+
struct S<T> {
421+
a: u32,
422+
_: union {
423+
b: T,
424+
c: u64,
425+
}
426+
}
427+
```
428+
429+
You may also use a generic struct or union parameterized by a type as the named
430+
type of an unnamed field, since the compiler can know all the resulting field
431+
names at declaration time without knowing the generic type:
432+
433+
```rust
434+
#[repr(C)]
435+
struct S<T> {
436+
a: u32,
437+
_: U<T>,
438+
_: U2<u64>,
439+
}
440+
```
441+
442+
However, you cannot use a type parameter itself as the named type of an unnamed
443+
field:
444+
445+
```rust
446+
#[repr(C)]
447+
struct S<T> {
448+
a: u32,
449+
_: T, // error
450+
}
451+
```
452+
453+
This avoids situations in which the compiler must delay producing an error on a
454+
field name conflict between `T` and `S` (or on the use of a non-struct,
455+
non-union type for `T`) until it knows a specific type for `T`.
456+
414457
# Reference-level explanation
415458
[reference-level-explanation]: #reference-level-explanation
416459

@@ -503,6 +546,15 @@ and `_: struct { fields }`, we could omit the field name entirely, and write
503546
match the C syntax. However, this does not provide as natural an extension to
504547
support references to named structures.
505548

549+
## Allowing type parameters
550+
551+
We could allow the type parameters of generic types as the named type of an
552+
unamed field. This could allow creative flexibility in API design, such as
553+
having a generic type that adds a field alongside the fields of the type it
554+
contains. However, this could also lead to much more complex errors that do not
555+
arise until the point that code references the generic type. Prohibiting the
556+
use of type parameters in this way will not impact common uses of this feature.
557+
506558
## Field aliases
507559

508560
Rather than introducing unnamed fields, we could introduce a mechanism to

0 commit comments

Comments
 (0)