Search code examples
rusthashmap

How can i convert this match statement into a HashMap?


How could I convert this match block into a HashMap? Ideally I would like to create a HashMap from a manifest file:

match layers[1][p] {
    ',' => tile = grass,
    '*' => tile = sand,

    // And so on....
}

I tried doing this earlier, but Macroquad's Texture2D is not compatible with a HashMap. (I think the compiler said 'Cannot use Option as Texture2D'.)

I would like to do something like this:

let tile = hashmap.get(layers[p]);
blit(tile);

Solution

  • Let's keep this simple. I don't think hashmap will simplify anything but why not demonstrate it. The true advantage of hash is that you can load tiles dynamically and make them loaded into the map. For now, though, we will hardcode some.

    
    fn main() {
        
        /* snip */
        let mut textures = HashMap::new();
        textures.insert(',', grass);
        textures.insert('*', sand);
    
        /* snip */
        
        // mind that your program will crash if map does 
        // not contain the texture
        let texture = textures.get(layers[p]).unwrap();
        blit(texture)
    }