在Rust中缓存资源的惯用方法

B1C*_*0PS 4 rust

我是Rust的新手,我正在用活塞发动机进行一场比赛,让我的脚湿润.

我想使用精灵表来渲染一堆实体,但很多实体可能会共享精灵表,所以我只想加载和存储每个文件的一个副本.

在伪代码中,我的方法基本上是这样的:

fn get_spritesheet(hashmap_cache, file):
    if file not in hashmap_cache:
        hashmap_cache[file] = load_image_file(file)

    return hashmap_cache[file]
Run Code Online (Sandbox Code Playgroud)

那么可能是这样的:

//These 'sprite' fileds point to the same image in memory
let player1 = Entity { sprite: get_spritesheet(cache, "player.png") };
let player2 = Entity { sprite: get_spritesheet(cache, "player.png") }; 
Run Code Online (Sandbox Code Playgroud)

但是,我正在使用Rust的所有权系统遇到很多障碍(可能是因为我不理解它).

据我所知,我希望cahe/hashmap"拥有"图像资源.具体来说,返回引用(如在get_spritesheet函数中)似乎很奇怪.此外,结构是否可能不拥有其所有成员?我想是的,但我对如何做到这一点很困惑.

Tim*_*ann 6

std::collections::hash_map::Entry是为了什么:

查看地图中的单个条目,可以是空置或占用.

match hashmap_cache.entry(key) {
    Entry::Vacant(entry) => *entry.insert(value),
    Entry::Occupied(entry) => *entry.get(),
}
Run Code Online (Sandbox Code Playgroud)

如果条目是空的,则将值插入高速缓存中,否则从高速缓存接收该值.

操场