Amandasaurus
Amandasaurus

Reputation: 60649

Rebinding a variable not working inside a for loop

I'm trying to write a loop that iterates a number of times, which also updates a variable in Rust.

fn get_next(input: &[u8]) -> (u8, &[u8]) {
    (input[0], &input[1..])
}

fn main() {
    let slice: &[u8] = &vec![1, 2, 3, 4];
    for _ in 0..4 {
        let (mynum, slice) = get_next(slice);
        println!("Here's mynum {} slice {:?}", mynum, slice);
    }
}

Code is on the Rust Playground.

This is the output:

Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]
Here's mynum 1 slice [2, 3, 4]

I would expect the slice variable to be changed each time to point to the next sub slice. How can I get the slice variable to be updated?

This is a minimum example, if I really were iterating over u8's in a slice, I'd do it differently.

Upvotes: 2

Views: 196

Answers (1)

Ms2ger
Ms2ger

Reputation: 76

You're defining a new variable that shadows the outer one. Perhaps:

let mut slice: &[u8] = &vec![1, 2, 3, 4];
for _ in 0..4 {
    let (mynum, slice_) = get_next(slice);
    slice = slice_;
    println!("Here's mynum {} slice {:?}", mynum, slice);
}

Upvotes: 6

Related Questions