如何使用格式的动态格式字符串!宏? [英] How can I use a dynamic format string with the format! macro?
问题描述
格式!
宏来格式化 String
。作为格式!
需要一个文字,我不能将我的字符串传递给它。我想这样做动态添加字符串到当前字符串在视图引擎中使用。 let test = String :: from(测试:{});
let test2 = String :: from(Not working!);
println!(test,test2);
实际上我想实现的是下面的例子,其中main.html包含 {content}
。
使用std :: io :: prelude :: *
使用std :: fs :: File;
使用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) - >结果<(),io :: Error> {
let mut file = try!(File :: open(main.html));
try!(file.read_to_string(buffer));
OK(())
}
所以我想打印内容
简单回答:不能这样做。
长答案:格式!
宏(及其衍生物)需要一个字符串字面值,即编译时已知的字符串。为了交换这个要求,如果提供的参数与格式不匹配,就会出现编译错误。
正在寻找被称为模板引擎。 Rust模板引擎列表没有特定的顺序:
模板引擎具有不同的特性,并且在编译时或运行时发生验证的程度和灵活性有很大不同(我似乎回想一下,Maud是非常以HTML为中心的)。这是由你找到一个最适合你的用例。
I just started learning Rust, and I'm making some small tools to help me understand the language. I have a problem formatting a String
using the format!
macro. As format!
takes a literal, I am not able pass my string 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);
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(())
}
So I want to print the contents of main.html after I formatted it.
Short answer: it cannot be done.
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.
What you are looking for is known as a template engine. A non-exhaustive list of Rust template engines in no particular order:
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屋!