PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] How to reference 2d array?

 July 10, 2022     arrays, reference, rust     No comments   

Issue

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 }
    }
}

Solution

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>>.



Answered By - wannabe
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing