Consider the code:
fn process_partition(v: Vec<String>) {
println!("{:?}", v);
}
pub fn main() {
let data = vec![
"Hello".to_string(),
"World".to_string(),
"-".to_string(),
"Public".to_string(),
"Park".to_string(),
];
let mut partition = vec![];
for d in data {
if d == "-" {
process_partition(partition); // Value moved here
partition = vec![]; // Reinitialised
} else {
partition.push(d);
}
}
process_partition(partition);
}
I was surprised that this compiles and works. Specifically, the moving of value inside the for-loop and then subsequent access being allowed by the borrow checker:
if d == "-" {
process_partition(partition); // Value moved here
partition = vec![]; // Reinitialised
} else {
partition.push(d);
}
My hunch was that the borrow checker is able to detect the re-initialisation and therefore is allowing the same. Went ahead and commented out the re-initialisation part and the borrow checker flagged the violation of rules.
if d == "-" {
process_partition(partition); // Value moved here
// Commented out and fails borrow checker tests
// partition = vec![];
}
Is it indeed because of re-initialisation or are there some other rules at play?