Construction Site @adotinthevoid @jdonszelmann @Victoronz @GoldsteinE @WaffleLapkin @BoxyUwU
// 1.
struct Struct {}
struct Tuple(u32);
struct Unit;
fn main() {
Struct;
Tuple;
Unit;
}
// 2.
struct Struct {}
struct Tuple(u32);
struct Unit;
fn main() {
Struct {};
Tuple { 0: 1_u32 };
Unit {};
}
Solution
There are 3 kinds of structs in Rust:
- Plain structs (eg
struct Foo { bar: i32 }) - Tuple structs (eg
struct Bar(i32);) - Unit structs (eg
struct Baz;)
The name of a plain struct refers to the type of the struct.
The name of a tuple struct either refers to the type of the struct or the implicit function used to construct it:
struct Tuple(u32);
// conceptually desugars to...
struct Tuple { 0: u32 }
fn Tuple(0: u32) -> Tuple { /* not important */ }
The name of a unit struct either refers to the type of the struct or the implicit constant representing its only value.
struct Tuple;
// conceptually desugars to...
struct Tuple { }
const Tuple: Tuple = /* not important */;
// 1.
error[E0423]: expected value, found struct `Struct`
--> examples/misc_9_1.rs:9:5
|
4 | struct Struct {}
| ---------------- `Struct` defined here
...
9 | Struct;
| ^^^^^^ help: use struct literal syntax instead: `Struct {}`
For more information about this error, try `rustc --explain E0423`.
error: could not compile `code` (example "misc_9_1") due to 1 previous error
In the first example both Unit and Tuple are valid expressions, evaluating to either the only value of the Unit type or the function item for the constructor of Tuple.
Struct however is not a valid expression as it simply refers to the type of the struct.
// 2.
In the second example, perhaps surprisingly, all of Unit {}, Tuple { 0: 1_u32 } and Struct {} are valid.
Both tuple and unit structs both support Struct {} syntax as it is useful for macros.
Another interesting example would be the interactions between Unit's constant and destructuring assignment:
// 3.
struct Struct {}
struct Tuple();
struct Unit;
fn main() {
Struct = loop {};
Tuple = loop {};
Unit = loop {};
}
error[E0423]: expected value, found struct `Struct`
--> examples/misc_9_3.rs:9:5
|
4 | struct Struct {}
| ---------------- `Struct` defined here
...
9 | Struct = loop {};
| ^^^^^^ help: use struct literal syntax instead: `Struct {}`
error[E0070]: invalid left-hand side of assignment
--> examples/misc_9_3.rs:10:11
|
10 | Tuple = loop {};
| ----- ^
| |
| cannot assign to this expression
Some errors have detailed explanations: E0070, E0423.
For more information about an error, try `rustc --explain E0070`.
error: could not compile `code` (example "misc_9_3") due to 2 previous errors
Unit is a valid pattern as it actually refers to the constant representing the only value of the unit struct.
Tuple and Struct however are not valid patterns as they are a path to a function and a path to a type.