envfmt: Escape a Dollar Sign

Escape a Dollar Sign

A short guide on how to get a literal dollar sign ($) in your final string.

The dollar sign $ is special in envfmt. It tells the formatter to look for a variable. But what if you need an actual dollar sign in your output, like for showing gas fees in USD?

The fix is simple: just use a double dollar sign, $$. When envfmt sees $$, it replaces it with a single $.

Example: Showing Gas Fees

Let’s say you want to create a string like Estimated gas fee: $5. If you write $5, envfmt will think you’re trying to expand a variable named 5, which isn’t a valid name.

Here’s how you do it correctly:

src/main.rs
fn main() {
    let template = "Estimated gas fee: $$5 in USD.";
    let message = envfmt::format(template).unwrap();
    println!("{}", message);
}

When you run this, the output will be exactly what you want:

Plain Text
Estimated gas fee: $5 in USD.

This works for both envfmt::format() and envfmt::format_with(). The parser is simple, it just looks for a $ and then checks the next character. If it’s another $, it outputs one and moves on.

You can mix escaped dollar signs and variables in the same string too.

src/main.rs
use std::collections::HashMap;

fn main() {
    let mut context = HashMap::new();
    context.insert("NETWORK", "mainnet");

    let template = "Gas on $NETWORK can be $$5 or more.";
    let message = envfmt::format_with(template, &context).unwrap();
    println!("{}", message);
}

Running this will produce:

Plain Text
Gas on mainnet can be $5 or more.