I am reading Mastering Rust. There is an exercise at the end of the first chapter where sample code is provided, and the task is to fix it, iterating by using the generally quite helpful compiler error messages.
I was expecting that the following was an error but it is not:
for line in reader.lines() {
let line = line.expect("Could not read line.");
For complete context, I have the entire code in a gist. That's the code after I fixed things, and the relevant rows are 37 & 38. However it requires feeding a text file as an argument.
I was expecting an error because line
is on the stack (at least the pointer is). Is it right that it can still be destroyed and replaced with no complaint?
What happens under the hood regarding memory management and the stack? I presume that line
is actually a reference to a string (a &str
type). So, then, this is fine because in either case, the pointer itself - the object on the stack - is just a usize
, so that both line
objects are of the same size on the stack.
Can I do this with something of a different size? Could the second line have said:
let line: f64 = 3.42;
In this case, the object itself is on the stack, and it is potentially larger than usize
.