Why does the compiler return the following error? I mean: if all possible code path (every match brace) assigns the structure fields of the return value struct, why rustc complains?
error[E0381]: use of possibly uninitialized variable: `x`
--> src/main.rs:37:5
|
37 | x
| ^ use of possibly uninitialized `x`
This is issue #31947, which was marked as a duplicate of related issue #21232. According to the discussion there, this code may become valid in the future (i.e., it will be possible to read from a struct after each of its fields has been initialized separately).
I didn’t even realize that you can assign to struct field individually before initializing the whole struct. It feels like a noob trap.
It was probably a C-ism that's crept into the language. Initializing each member individually feels like a great way to accidentally leave something uninitialized, leading to the fun memory issues that Rust is designed to avoid.
I'd actually vote for assigning to fields individually before initialization to be a compile error (or at least a default-on warning) because it's a great way to shoot yourself in the foot. It's usually an anti-pattern in Rust anyway.