Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing two dimensional arrays to functions in Rust

Does anybody know how to pass a two dimensional array to function in Rust? The function needs to change values of array.

This is how I create array:

let state=[mut [mut 0u8, ..4], ..4];

Thanks.

like image 588
php-- Avatar asked Dec 21 '25 16:12

php--


1 Answers

(nb: rust 0.5, which wasn't yet out when this question was asked)

The stupid way to find out the type of a value is to write a function with the wrong type, then try to pass it. :)

fn func(state: int) {}

produces:

error: mismatched types: expected `int` but found `[mut [mut u8]/4]/4` (expected int but found vector)

So that's your type. Except it's not actually written like that any more, so it seems there's a bug in this output. So much for just asking the compiler. You actually want:

fn func(state: [mut [mut u8 * 4] * 4]) { ... }

But mut inside vectors is sorta deprecated; you can get the same effect by making the variable itself mut. That brings us to:

let mut state = [[0u8, ..4], ..4];
func(state);

// ...

fn func(state: [[u8 * 4] * 4]) {}

And if you want to actually change state inside the function, you'll need a mutable pointer to it, so finally:

let mut state = [[0u8, ..4], ..4];
func(&mut state);

// ...

fn func(state: &mut [[u8 * 4] * 4]) {}
like image 86
Eevee Avatar answered Dec 23 '25 07:12

Eevee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!