Created
November 24, 2017 10:03
-
-
Save convexbrain/d6784659068f87290e9a50f71dd13e1f to your computer and use it in GitHub Desktop.
Rust 2D slice example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
/* | |
* 1D array and slice | |
*/ | |
let array = [11u8, 12, 13, 14, 15]; // 1D array: 5 elems | |
let slice: &[u8] = &array; // slice of 1D array | |
for x in slice { // x: &u8 | |
print!("{} ", x); | |
} | |
println!(); | |
println!("---"); | |
/* | |
* 2D array(mutable) and slice | |
*/ | |
let mut array = [[0u8; 3]; 5]; // 2D array: 5rows x 3cols | |
// set 2D array values to [[1, 2, 3], [4, 5, 6], ...] | |
let mut cnt = 0u8; | |
for row in &mut array { // row: &mut [u8; 3] | |
for col in row { // col: &mut u8 | |
cnt += 1; | |
*col = cnt; | |
} | |
} | |
let mut vec: Vec<&[u8]> = Vec::new(); // vector containing &[u8] which is type of 1D slice | |
// first, make vector of row slices | |
for row in &array { | |
vec.push(row); | |
} | |
let slice: &[&[u8]] = &vec; // slice of 2D array by slicing vector | |
for row in slice { // row: &&[u8] | |
for col in *row { // col: &u8 | |
print!("{} ", col); | |
} | |
println!(); | |
} | |
} |
Create a 2D slice and pass it to a function
use std::fmt::Display;
fn print2dslice<T: Display>(two2darr: &[&[T]]) {
for (row_idx, row) in two2darr.iter().enumerate() {
println!("");
for (col_idx, elt) in row.iter().enumerate() {
print!("[{} {} {}] ", row_idx, col_idx, elt);
}
}
}
fn main() {
// * Create a 2D slice.
let twoarray: [[u64; 4]; 5] = [[0u64; 4]; 5];
let mut vector_slice_rows = Vec::new();
for row in &twoarray {
vector_slice_rows.push(&row[..]);
}
let sliceofslice: &[&[u64]] = vector_slice_rows.as_slice();
print2dslice(&sliceofslice);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
>cargo run
11 12 13 14 15
---
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15