从for循环返回修改后的数组,没有类型不匹配

时间:2017-07-01 21:10:51

标签: rust

在伪代码中,我正在尝试执行以下操作:

my_array = [[1,2,3,4],[5,6,7,8]]
my_array = array_modify_fn(my_array)

fn array_modify_fn(array) {
    for i in array {
        array[i] = some_operation
    }
}

阅读this question关于类型不匹配的这种循环/函数会导致在Rust中,我仍然对如何实际实现我想在这里实现的内容感到困惑,但在Rust中。

我是否只是以错误的方式解决问题? (对于Rust至少;这是我在Python中的方法。)

我的Rust现在看起来像这样:

let mut life_array = [[false; SIZE]; SIZE];
life_array = random_init(&mut life_array); // in main function

fn random_init(arr: &mut [[bool; SIZE]; SIZE]) -> [[bool; SIZE]; SIZE] {
    for i in 0 .. (SIZE*SIZE) {
        arr[i/SIZE][i%SIZE] = rand::random()
    }
}

,这会返回类型不匹配:expected type '[[bool; SIZE]; SIZE]' found type '()'

1 个答案:

答案 0 :(得分:3)

您已使用返回类型定义random_init,但您的函数不返回任何内容(严格来说,它返回())。由于你是在就地改变数组,你的函数不必返回任何东西,所以你应该省略返回类型。

const SIZE: usize = 4;

extern crate rand;

fn main() {
    let mut life_array = [[false; SIZE]; SIZE];
    random_init(&mut life_array);
}

fn random_init(arr: &mut [[bool; SIZE]; SIZE]) {
    for i in 0..(SIZE * SIZE) {
        arr[i / SIZE][i % SIZE] = rand::random()
    }
}
相关问题