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"