gpt4 book ai didi

function - Rust 函数如何修改数组索引的值?

转载 作者:行者123 更新时间:2023-11-29 08:11:19 24 4
gpt4 key购买 nike

我的目标是让 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 做了很多 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

关于function - Rust 函数如何修改数组索引的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51089668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com