Late substitution

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!{})
);

You may want to rethink the name again because I fist thought of What are early and late bound parameters - Rust Compiler Development Guide. I suggest something like runtime_format.

2 Likes

Same functionality from another crate[1] I've seen lately


  1. I don't use it though ↩ī¸Ž

2 Likes

Agreed; it's now LateFormat:

https://crates.io/crates/late_format

There is an established crate for this: dyn_fmt - Rust

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.