Home > front end >  How to reference 2d array?
How to reference 2d array?

Time:04-22

Im trying to pass newly initialized 2d array of chars to the struct; It says that types do not match and I dont know how to do it properly;

Screenshot of code and error message

struct Entity<'a> {
    dimensions: Vec2,
    sprite: &'a mut[&'a mut [char]]
}

impl Entity {

    fn new<'a>() -> Self {

        let mut sp = [[' '; 3]; 4];
        for y in 0..sp.len() {
            for x in 0..sp[y].len() {
                sp[y][x] = '$';
            }
        }
    
        return Entity{dimensions: Vec2::xy(3, 4), sprite: &mut sp }
    }
}

CodePudding user response:

I think theres a couple things going on.

1.) &'a mut[&'a mut [char]] references a mutable slice containing mutables slices of chars. What you are constructing is a fixed array matrix of chars and then attempting to return mutable references to that. These are not interchangeable types.

2.) You are attempting to return references to data created within new, which is not going to work like that due to the lifetime of the local variables.

An alternative, which might be what you want is to define your struct to contain a fixed size array matrix. Like so:

struct Entity {
    sprite: [[char; 3]; 4]
}

impl Entity {

    fn new() -> Self {
    
        let mut sp = [[' '; 3]; 4];
        for y in 0..sp.len() {
            for x in 0..sp[y].len() {
                sp[y][x] = '$';
            }
        }

        return Entity{sprite: sp }
    }
}

Or you could even use const generics for different sizes:

struct Entity<const W: usize, const H: usize> {
    sprite: [[char; W]; H]
}

 impl<const W: usize, const H: usize> Entity<W, H> {

     fn new() -> Self {
    
        let mut sp = [[' '; W]; H];
        for y in 0..sp.len() {
            for x in 0..sp[y].len() {
                sp[y][x] = '$';
            }
        }
    
        return Entity{sprite: sp }
    }
}

If you cannot know the size of the sprite at time of compilation, you will need to define it using a dynamically sized data structure, such as a Vec. Ie., Vec<Vec<char>>.

  • Related