Reputation: 411
I'm playing with Rust a little bit, and got stuck. I've the following function:
fn addOne(h: (i32, i32, i32)){
let mut (x, y, z) = h;
(x+1, y+1, z+1)
}
This gives me the following error on compile:
example.rs:2:10: 2:11 error: expected identifier, found `(`
example.rs:2 let mut (x, y, z) = h;
Is there something wrong with the binding? Sorry if it is such a simple question.
Upvotes: 2
Views: 2007
Reputation: 430673
The mut
qualifier applies per-variable. When you are destructuring a variable, each variable can be mutable or not:
fn add_one(h: (i32, i32, i32)) -> (i32, i32, i32) {
let (mut x, mut y, mut z) = h;
(x+1, y+1, z+1)
}
Of course, you don't need mutability here at all:
fn add_one(h: (i32, i32, i32)) -> (i32, i32, i32) {
let (x, y, z) = h;
(x+1, y+1, z+1)
}
You could also choose to destructure in the function signature:
fn add_one((x, y, z): (i32, i32, i32)) -> (i32, i32, i32) {
(x+1, y+1, z+1)
}
Or use the default tuple accessor methods:
fn add_one(h: (i32, i32, i32)) -> (i32, i32, i32) {
(h.0 + 1, h.1 + 1, h.2 + 1)
}
If you want to mutate the tuple in place, you are going to need to provide a mutable reference to the tuple. Without knowing more about the problem you are trying to solve, I would actively discourage you from choosing this path, at least until you've profiled and determined you need it:
fn add_one(h: &mut (i32, i32, i32)) {
h.0 += 1;
h.1 += 1;
h.2 += 1;
}
fn main() {
let mut a = (1, 2, 3);
add_one(&mut a);
println!("{:?}", a)
}
There are lots of ways to write code that is meaningful to you!
Upvotes: 6