I've needed this several times in different languages and some folks here suggested use of template engines, however I don't need a complex engine, just wanted to replace simple parameters directly as if using format!(...)
.
The only thing missing with format!(...)
is that the string is compile-time and, for some use cases, the parameter name is also compile-time.
I've come up with a crate called apply-string-args
before, but the name was a little ugly, so I released a little improved crate:
use late_substitution::LateSubstitution;
use maplit::hashmap;
let user_string: String = "some user string: {id}".into();
assert_eq!(
"some user string: x",
user_string.late_substitution(hashmap!{"id".into() => "x".into()})
);
let user_string: String = r#"some user string: {"id"}"#.into();
assert_eq!(
"some user string: id",
user_string.late_substitution(hashmap!{"id".into() => "x".into()})
);
let user_string: String = r#"some user string: { "id" }"#.into();
assert_eq!(
"some user string: id",
user_string.late_substitution(hashmap!{"id".into() => "x".into()})
);
let user_string: String = "some user string: {id}".into();
assert_eq!(
"some user string: None",
user_string.late_substitution(hashmap!{})
);