Misc 9 @adotinthevoid @jdonszelmann @Victoronz @GoldsteinE
Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.
struct Unit;
struct Tuple();
struct Struct {}
fn main() {
Unit {};
Tuple {};
Struct {};
Unit();
Tuple();
Struct();
Unit;
Tuple;
Struct;
Unit { .. } = Unit { ..Unit };
Tuple { .. } = Tuple { ..Tuple() };
Struct { .. } = Struct { ..Struct {} };
}
Solution
error[E0423]: expected value, found struct `Struct`
--> examples/misc_9.rs:16:5
|
3 | struct Struct {}
| ---------------- `Struct` defined here
...
16 | Struct;
| ^^^^^^ help: use struct literal syntax instead: `Struct {}`
error[E0618]: expected function, found struct `Unit`
--> examples/misc_9.rs:10:5
|
1 | struct Unit;
| ----------- struct `Unit` defined here
...
10 | Unit();
| ^^^^--
| |
| call expression requires function
|
help: `Unit` is a unit struct, and does not take parentheses to be constructed
|
10 - Unit();
10 + Unit;
|
error[E0423]: expected function, tuple struct or tuple variant, found struct `Struct`
--> examples/misc_9.rs:12:5
|
3 | struct Struct {}
| ---------------- `Struct` defined here
...
12 | Struct();
| ^^^^^^^^ help: use struct literal syntax instead: `Struct {}`
Some errors have detailed explanations: E0423, E0618.
For more information about an error, try `rustc --explain E0423`.
error: could not compile `code` (example "misc_9") due to 3 previous errors
No matter what kind a struct is, it can always be initialized with braces (even if not declared with them). Therefore the first 3 statements are OK.
Only Tuple
structs can be initialized with parentheses, because it's actually calling a constructor function.
Unit;
on it's own is fine, because Unit
is declared as a unit struct, so Unit
is a constant of type Unit
.
Tuple;
on it's own is fine, because Tuple
as a value is the constructor for Tuple
, with type fn() -> Tuple
.
Struct;
is a compiler error, because Struct
only exists as a type, and never a value.
Destructuring assignment on a unit structs works as any other struct, and struct update syntax as well, even when there are no fields.