use*_*725 1 parameters function increment 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
Run Code Online (Sandbox Code Playgroud)
编译器报告以下错误:
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`
Run Code Online (Sandbox Code Playgroud)
如何使函数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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
790 次 |
| 最近记录: |