I want to make a function that receives a Vec and a position to change a number.
Rust has indexing syntax, just like JavaScript, so there's really no need for the destructuring.
fn replace_number(mut line: Vec<i32>, point: usize, number: i32) -> Vec<i32> {
line[point] = number;
line
}
or, more idiomatically:
fn replace_number(line: &mut Vec<i32>, point: usize, number: i32) {
line[point] = number
}
Even more idiomatically would be to not have this function, probably, and just write it inline...
I want to know about immutably adding
With your original code, there's zero concern about anything "bad" happening because of mutability:
fn replace_number(line: Vec<i32>, point: i32, number: i32) -> Vec<i32>
This function takes ownership of the Vec
, so the concept of immutability is rather moot here — the caller no longer has the Vec
to care if it's mutated or not!
If you wanted to share data, you'd use a reference (a slice, specifically) like &[i32]
. This is inherently immutable — you can't change it if you wanted to. You'd have to clone all the children and make the vector mutable:
fn replace_number(line: &[i32], point: usize, number: i32) -> Vec<i32> {
let mut line = line.to_owned();
line[point] = number;
line
}
If you really wanted something like the JS syntax, you can use concat
:
fn replace_number(line: &[i32], point: usize, number: i32) -> Vec<i32> {
[&line[..point], &[number], &line[point + 1..]].concat()
}
See also: