I'm very new in Rust, and I would like to implement a 2D map. So I have a map structure with inside width, height and the data pointer with unknown size until calling a load_map function which parse a file and then initialize the map structure. In C language I would do:
struct map {
uint32_t width;
uint32_t height;
uint8_t *data;
};
int load_map(struct map *m)
{
... parse a file and found a map with height=width=8
m->width = 8;
m->height = 8;
// allocate map data using the map size we found
m->data = (uint8_t *)malloc(m->width * m->height);
...
}
In Rust, I have no idea how to achieve something that simple ! Here is my failing attempt:
struct Map<'a> {
width: usize,
height: usize,
data: &'a mut u8
}
fn load_map() -> Map<'static>
{
//code that parse a file and found a map with height=width=8
...
const w:usize = 8;
const h:usize = 8;
//allocate the map data
let mut data = [0;w*h];
// create the map structure
let mut m = Map {
width: w,
height: h,
data: data
};
m
}
fn main() {
let mut m: Map;
m = load_map();
println!("Hello, world! {} {}", m.height, m.width);
}
But cargo is not happy and throw me this error:
error[E0308]: mismatched types
--> src/main.rs:16:15
|
16 | data: data
| ^^^^ expected `&mut u8`, found array `[{integer}; 64]`
error: aborting due to previous error
I do understand the error: rust is expecting the same type of data for data. But I have no clue on how to achieve that. The Map struct is generic and there is no way we can know the data size before parsing the file. It seems that we should be able to declare the data bytes in init_map and give ownership to Map structure, right ? But how ?