Cache the result of a function HashMap

cached HashMap

Caching the result of a function using the cached crate

examples/cache-hashmap-result-of-function/src/main.rs

use std::collections::HashMap;
use cached::macros::cached;

fn main() {
    let config = get_config();
    println!("Config: {:?}", config);

    let config = get_config();
    println!("Config: {:?}", config);
}


#[cached]
fn get_config() -> HashMap<&'static str, String> {
    println!("get_config called");

    let mut config = HashMap::new();
    config.insert("city", String::from("Seoul"));
    config.insert("country", String::from("Korea"));
    config
}




The function runs only once.

examples/cache-hashmap-result-of-function/out.txt

get_config called
Config: {"country": "Korea", "city": "Seoul"}
Config: {"country": "Korea", "city": "Seoul"}

examples/cache-hashmap-result-of-function/Cargo.toml

[package]
name = "cache-hashmap-result-of-function"
version = "0.1.0"
edition = "2024"

[dependencies]
cached = "2.0.2"

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo