How to Use a HashMap for Variables
Shows how to use your own data, like a HashMap, instead of environment variables.
Sometimes, your variables don’t come from the environment. Maybe you’re loading
them from a config file, getting them from a database, or building them inside
your program. For these cases, you can use envfmt::format_with().
This function is more flexible than format(). It lets you provide your own
data source as long as it implements the Context trait. The good news is that
HashMap already works out of the box.
The format_with() Function
The format_with() function takes two arguments:
input: The template string you want to format.context: A reference to your data source, like aHashMap.
Let’s see how it works.
Using a HashMap as Context
In your src/main.rs, let’s create a HashMap and use it to format a string.
use std::collections::HashMap;
fn main() {
// 1. Create your context
let mut context = HashMap::new();
context.insert("RPC_URL".to_string(), "http://localhost:8545".to_string());
// You could load your context from a config file.
// ...
// 2. Define the template
let template = "Using RPC URL: ${RPC_URL}";
// 3. Format the string using your context
let message = envfmt::format_with(template, &context).unwrap();
println!("{}", message);
}Now, run the program:
cargo runThe output will be:
Using RPC URL: http://localhost:8545As you can see, envfmt used the values from our HashMap instead of looking
at the environment. This is really useful because it lets you use envfmt as a
simple templating tool for any data you have.
Why This Works
envfmt can use a HashMap because it implements a special trait called
Context. This trait just tells envfmt how to look up a variable by its name.
I’ve already implemented it for HashMap<String, _> and HashMap<&str, _> so
you don’t have to.