How can a Rust function modify the value of an array index?
Asked Answered
S

1

5

My goal is to have the Rust function f increment an element of array x, and increment the index i:

fn main() {
    let mut x: [usize; 3] = [1; 3];
    let mut i: usize = 1;
    f(&mut i, &mut x);
    println!("\nWant i = 2, and i = {}", i);
    println!("\nWant x = [1,2,1], and x = {:?}", x);
} // end main

fn f(i: &mut usize, x: &mut [usize]) {
    x[i] += 1;
    i += 1;
} // end f

The compiler reports the following errors:

error[E0277]: the trait bound `&mut usize: std::slice::SliceIndex<[usize]>` is not satisfied
  --> src/main.rs:10:5
   |
10 |     x[i] += 1;
   |     ^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[usize]>` is not implemented for `&mut usize`
   = note: required because of the requirements on the impl of `std::ops::Index<&mut usize>` for `[usize]`

error[E0368]: binary assignment operation `+=` cannot be applied to type `&mut usize`
  --> src/main.rs:11:5
   |
11 |     i += 1;
   |     -^^^^^
   |     |
   |     cannot use `+=` on type `&mut usize`

How do I make the function f increment both an element of its array parameter x and the index i (also a parameter)?

Sought answered 28/6, 2018 at 18:59 Comment(1)
Simply, i => *iSoloma
I
7

You need to dereference i. This can be confusing because Rust does a lot of auto dereferencing for you.

fn main() {
    let mut x: [usize; 3] = [1; 3];
    let mut i: usize = 1;
    f(&mut i, &mut x);
    println!("\nWant i = 2, and i = {}", i);
    println!("\nWant x = [1,2,1], and x = {:?}", x);
} // end main

fn f(i: &mut usize, x: &mut [usize]) {
    x[*i] += 1;
    *i += 1;
} // end f

playground

Insulator answered 28/6, 2018 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.