Hello, this is my first forum post. I've been reading through the rust book and trying to work on some basic implementations of linear algebra stuff in rust and came across this code that doesn't compile
fn main() {
let a: [usize; 1];
a[0] = 2;
println!("{}", a[0]);
}
this is what the compiler outputs when given the code:
error[E0381]: used binding `a` isn't initialized
--> temp3.rs:4:5
|
2 | let a: [usize; 1];
| - binding declared here but left uninitialized
3 |
4 | a[0] = 2;
| ^^^^ `a` used here but it isn't initialized
|
help: consider assigning a value
|
2 | let a: [usize; 1] = [42; 1];
| +++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0381`.
i understand that this can be fixed by just initializing the array with any number but i was wondering why exactly the compiler refuses to compile this, does it somehow result in possible unsafe patterns?
It's because the language doesn't differentiate between compile-time known and compile-time unknown expressions in the same position. In a position where a runtime value is allowed, all expressions are treated as runtime values. So this:
let a: [usize; 2];
a[0] = 1;
a[1] = 2;
is treated by the data flow analysis the same way as:
let a: [usize; 2];
a[unknown1()] = 1;
a[unknown2()] = 2;
and in the latter there is no way to know whether the entries have been initialized.
there's difference between initializing an array variable binding and assigning a (newly initialized) value to an array element.
let a: SomeType declares the variable of a, but it is in an uninitialized state. the only valid code after the declaration is to initialize the variable (as a whole) with a valid value of that type, i.e. a = some_value; it's not allowed to initialize the value "piece by piece".
in your example, the pieces are individual elements of the array, another example is individual fields of a struct.
in other words:
// declaration
let a: [usize; 1];
// this is valid initialization
a = [2];
// control flows are checked, so this is valid too
if some_condition {
a = [2];
} else {
a = [3];
}
// but this is not valid
a[0] = 2; //<-- error: binding isn't initialized
in rust, if you want to construct some value incrementally, in-place, for any reason, you are required to use unsafe explicitly through raw pointers, typically combined with MaybyeUninit or alloc, and sometimes Pin too, if the object to be constructed needs stable address.
I see, so the compiler checks for initialization of the whole thing and not if you initialized every element of it as a memory safe feature. Thank you very much for the answer!
i failed to understand some things about the explanation, what exactly do you mean with "position" and what would the unknown() command be?