在某些情况下,我需要从服务器接收模板格式字符串,同时在脱机时提供默认值
过去我用过"小胡子"https://github.com/nickel-org/rust-mustache但是对于我的需求来说,这是一个很大的杀伤力。
例如from server:
变异1:
"Hello {}, how are you"
2:
变异
"Shalom {}, how are you"
在这两种情况下,字符串都有1 "插值"占位符。
我还想实现一个default
字符串与1插值占位符当服务器不提供模板。
我的问题是,如何创建一个"部分应用"format!
可字符串,这可以在稍后插入点?
我的意思的另一个例子:
// the server sends this object
#[derive(Serialize,Deserialize,Clone,Debug)]
struct Message {
text: String
}
// if the server doesn't provide a message, use a default
impl Default for Message {
fn default() -> Self {
Self {
text: "Hello {what do I put here so that I can plug a value in?}, how are you?"
}
}
}
let my_message: Message = get_message_template(); // get the message template or a default template
// now plugin the text
format!("{{{{my_message}}}}", "John"); //<<< how can I plug it in?
我认为有两种方法:
- 创建一个具有唯一模式的字符串常量,然后使用replace()将其替换为运行时值
- 将字符串分解为单独的字符串常量,然后将它们与稍后的运行时值连接起来
解决方案1可能像这样:
let greeting = "Hello {NAME}, how are you";
let name = "John";
println!("{}", greeting.replace("{NAME}", name));
解决方案2可能像这样:
let greeting_0 = "Hello ";
let greeting_1 = ", how are you";
let name = "John";
println!("{}{}{}", greeting_0, name, greeting_1);
我刚刚运行了这两个程序,它们似乎都能满足你的要求。