I know that one can destructure tuples and other things in let statements:
fn foo() -> (u8, u8) {
(1, 2)
}
fn main() {
let (x, y) = foo();
println!("{}, {}", x, y); // prints "1, 2"
}
Since Rust 1.59 one can also re-use existing bindings:
fn main() {
let mut x = 0;
let mut y = 0;
println!("{}, {}", x, y); // prints "0, 0"
(x, y) = foo();
println!("{}, {}", x, y); // prints "1, 2"
}
I'm wondering if there's a way to mix both, that is re-use an existing binding for some of the variables in the pattern and create new bindings for others. Something like the following (which doesn't compile):
fn main() {
let mut x = 0;
println!("{}", x);
(x, let y) = foo();
println!("{}, {}", x, y);
}
No, this is not possible.
It was outlined as a future possibility in the RFC, and discussed some times since, but neither RFC'd nor implemented.
There are two workarounds: either use let to declare all variables and assign one after, or use let before the assignment:
// Either:
fn main() {
let mut x = 0;
println!("{}", x);
let y;
(x, y) = foo();
println!("{}, {}", x, y);
}
// Or:
fn main() {
let mut x = 0;
println!("{}", x);
let (x2, y) = foo();
x = x2;
println!("{}, {}", x, y);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With