function - Rust 函数如何修改数组索引的值?
问题描述
我的目标是让 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
. 这可能会令人困惑,因为 Rust 为您做了很多自动取消引用。
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
推荐阅读
- react-native - Error: While trying to resolve module 'prop-types' from file
- python - Django - 正/负整数字段取决于选择
- python-3.x - 如何使用用户令牌在 Python 3 中获取 facebook 用户事件?
- sql - 在执行一些随机使用plpgsql时如何将用户输入的值与数据库中的数据进行比较
- scheme - 拉平列表列表
- octave - 以八度显示符号表达式。矩阵乘法作为表达式而不是结果
- ssl - Is it possible to identify TLS info. in requests response?
- javascript - 如何获取数组中的键值元素 - ionic 3
- java - 使用流在java中进行内部连接
- firebase - Firebase 向 Google App Engine 发出经过身份验证的请求