如何使用带有格式的动态格式字符串!宏? [英] How can I use a dynamic format string with the format! macro?
问题描述
我想使用带有 String
作为第一个参数的 format!
宏,但是因为宏需要字符串文字,所以我无法传递任何不同的东西.
I want to use the format!
macro with a String
as first argument, but because the macro expects a string literal, I am not able pass anything different to it.
我想这样做是为了将字符串动态添加到当前字符串中,以便在视图引擎中使用.如果有更好的方法,我愿意提供建议.
I want to do this to dynamically add strings into the current string for use in a view engine. I'm open for suggestions if there might be a better way to do it.
let test = String::from("Test: {}");
let test2 = String::from("Not working!");
println!(test, test2);
我真正想要实现的是下面的示例,其中 main.html 包含 {content}
.
What I actually want to achieve is the below example, where main.html contains {content}
.
use std::io::prelude::*;
use std::fs::File;
use std::io;
fn main() {
let mut buffer = String::new();
read_from_file_using_try(&mut buffer);
println!(&buffer, content="content");
}
fn read_from_file_using_try(buffer: &mut String) -> Result<(), io::Error> {
let mut file = try!(File::open("main.html"));
try!(file.read_to_string(buffer));
Ok(())
}
所以我想在格式化后打印main.html的内容.
So I want to print the contents of main.html after I formatted it.
推荐答案
简答:做不到.
长答案:format!
宏(及其派生词)需要字符串文字,即编译时已知的字符串.作为此要求的交换,如果提供的参数与格式不匹配,则会引发编译错误.
Long answer: the format!
macro (and its derivatives) requires a string literal, that is a string known at compilation-time. In exchange for this requirement, if the arguments provided do not match the format, a compilation error is raised.
您正在寻找的就是所谓的模板引擎.不完整的 Rust 模板引擎列表,不分先后:
What you are looking for is known as a template engine. A non-exhaustive list of Rust template engines in no particular order:
模板引擎具有不同的特性,并且在编译时或运行时发生的验证程度及其灵活性方面存在显着差异(例如,我似乎记得 Maud 非常以 HTML 为中心).您可以自行决定是否找到最适合您的用例.
Template engines have different characteristics, and notably differ by the degree of validation occurring at compile-time or run-time and their flexibility (I seem to recall that Maud was very HTML-centric, for example). It's up to you to find the one most fitting for your use case.
这篇关于如何使用带有格式的动态格式字符串!宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!