Text Templates in Rust

Rust offers built-in support for creating dynamic content or showing customized output to the user with the std::fmt module. This module provides macros for formatting and printing text.

use std::fmt::Write;

fn main() -> std::fmt::Result {
    // We can create a new String and use it as a buffer for our template
    let mut buffer = String::new();

    // Templates are a mix of static text and expressions enclosed in
    // `{}` that are used to dynamically insert content.
    write!(&mut buffer, "Value is {}\n", "some text")?;
    println!("{}", buffer);

    // We can use the same format string with different types
    println!("Value: {}\n", 5);
    println!("Value: {:?}\n", vec!["Rust", "Go", "C++", "C#"]);

    // If the data is a struct we can use the `{:?}` format specifier to print
    // all fields of the struct. The fields should be public to be accessible.
    #[derive(Debug)]
    struct Person {
        name: String,
    }

    let person = Person {
        name: String::from("Jane Doe"),
    };
    println!("Person: {:?}\n", person);

    // The same applies to maps
    use std::collections::HashMap;
    let mut map = HashMap::new();
    map.insert("Name", "Mickey Mouse");
    println!("Map: {:?}\n", map);

    // Conditional printing can be done using normal Rust control flow
    let condition = true;
    println!("{}", if condition { "yes" } else { "no" });

    let empty_string = "";
    println!("{}", if !empty_string.is_empty() { "yes" } else { "no" });

    // Iteration through collections can be done using normal Rust loops
    let languages = vec!["Rust", "Go", "C++", "C#"];
    print!("Range: ");
    for lang in languages {
        print!("{} ", lang);
    }
    println!();

    Ok(())
}

To run the program, put the code in templates.rs and use rustc to compile it, then run the resulting executable:

$ rustc templates.rs
$ ./templates
Value is some text

Value: 5

Value: ["Rust", "Go", "C++", "C#"]

Person: Person { name: "Jane Doe" }

Map: {"Name": "Mickey Mouse"}

yes
no
Range: Rust Go C++ C#

This Rust code demonstrates similar functionality to the original example, using Rust’s formatting macros and standard library features. Note that Rust doesn’t have a built-in templating system like Go’s text/template, but it provides powerful string formatting capabilities through the std::fmt module.

The write! macro is used to write formatted text to a String, which can then be printed. For more complex templating needs, there are third-party crates available in the Rust ecosystem.

Rust’s strong type system and ownership model provide additional safety guarantees compared to Go, but the basic concepts of string formatting and dynamic content generation are similar.