This rust solution to interpolation to a here document seems rough: Please can anyone suggest something better?

65 views Asked by At
use std::borrow::Cow;
use std::collections::HashMap;

fn interpolate_hash_values<'life>(my_heredoc: &'life str, my_values: HashMap<&'life str, &'life str>) -> Cow<'life, str> {
    let mut tmp = Cow::from(my_heredoc);

    for (key, value) in my_values {
        let lid = format!("#{{{}}}", key);
        tmp = tmp.replace(&lid, &value).into();
    }
    tmp
}

fn main() {
    let myvalues: HashMap<&str, &str> = HashMap::from([
        ("ThisThing", "Now is the time for all good beings to come to fix up rust to be much better."),
        ("ThatThing", "Or else."),
        ("TheOtherThing", "What???????????????????????????????????????????????"),
    ]);
    let mut myheredoc = String::from(r#"
    <html>
    <head>
    <title>Simle Here Document</title>
    </head>
    <body>
    <h3>Simle Here Document</h3>
    <p>
    Now is the time for all good denizens to play a companionable part.
    <p></p>
    #{ThisThing}
    <p></p>
    #{ThatThing}
    <p></p>
    #{TheOtherThing}
    </p>
    </body>
    </html>
    "#);
    println!("Here's the here doc before interpolations:  {}", myheredoc);
    let myresultstring = interpolate_hash_values(&mut myheredoc,myvalues);
    println!("Here's the here doc after interpolations:  {}", myresultstring);
}

This is to try to accomplish the interpolation to a here document function one might engage in Ruby, or most other such scripting languages. The solution works, but is complicated enough, I fear there must be a better way; perhaps one that makes the above code look foolish.

0

There are 0 answers