I am using an offset
variable to track the iteration position, and modifying / returning it. Is the below considered bad practice in Rust? I ask this because I don't see dereferencing very often in code I have seen.
fn get_next_u16(input: &[u8], offset: &mut usize) -> u16 {
let next = ((input[*offset+1] as u16) << 8) +
(input[*offset] as u16);
*offset += 2;
next
}
fn main() {
let input = [1, 2, 3, 4];
let mut offset = 0;
let first_u16 = get_next_u16(&input, &mut offset);
let second_u16 = get_next_u16(&input, &mut offset);
println!("first: {}", first_u16);
println!("second: {}", second_u16);
}
The other way I think of doing this is to reassign to the offset variable like:
fn get_next_u16(input: &[u8], offset: usize) -> (usize, u16) {
(offset+2, ((input[offset+1] as u16) << 8) +
(input[offset] as u16))
}
fn main() {
let input = [1, 2, 3, 4];
let offset = 0;
let (offset, first_u16) = get_next_u16(&input, offset);
let (offset, second_u16) = get_next_u16(&input, offset);
println!("first: {}", first_u16);
println!("second: {}", second_u16);
}
This looks cleaner but now you have to reassign to offset all the time.
Perhaps there is another way to do this also?