【问题标题】:How can a Rust function modify the value of an array index?Rust 函数如何修改数组索引的值?
【发布时间】:2018-06-28 18:59:11
【问题描述】:

我的目标是让 Rust 函数 f 增加数组 x 的一个元素,并增加索引 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

编译器报以下错误:

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`

如何使函数f 增加其数组参数x 的元素和索引i(也是一个参数)?

【问题讨论】:

  • 简单地说,i => *i

标签: function parameters rust increment


【解决方案1】:

您需要取消引用i。这可能会让人感到困惑,因为 Rust 为您做了很多 auto dereferencing

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

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多