-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
lint assigning to fields of an uninitialized struct #1058
Comments
Access to |
So there is no way to use that whatsoever? |
This recently came up on the user forums where a user was trying to assign to fields individually to "initialize" something. Quoting myself:
There should probably be a lint which detects where someone has declared a variable, then tried to initialize it, or its fields individually, later on. i.e. struct Point {x: u32, y: u32}
let mut p: Point;
p.x = 0; // <- warning: assigning to field of uninitialized variable.
// help: try to initialize with `let p = Point { ... }` instead.
p.y = 92;
// this also a C-ism and should be a warning in straight-line code (i.e. not forward
// declaring before initializing in a loop or if statement)
let p: Point;
p = Point { x: 7, y: 42 }; // <- warning: unnecessary forward declaration followed by an assignment
// help: prefer to initialize with `let p = Point { ... }` instead. |
I would be careful here – while it's an anti pattern in most circumstances, there are occasions where it is actually useful to be able to defer parts of initialisation. OTOH, I personally haven't seen this come up often in code, but then again, I often adopt a rather functional stance around initialisation anyway. I'd absolutely would support this as a restriction lint. |
It seems the compiler does not allow such code anymore. |
https://users.rust-lang.org/t/assigning-to-uninitialised-struct/6366/5
and
The text was updated successfully, but these errors were encountered: