In Rust, there is no built-in macro that directly replicates the exact functionality of Python's f-strings, where you can use variable names inside curly braces within the string itself. However, you can define your own macro to achieve a similar result.
Here's an example:
macro_rules! f_string {
($($tokens:tt)*) => {
format!($($tokens)*)
};
}
fn main() {
let my_name = "Santee";
let message = f_string!("{my_name} is cool");
println!("{}", message);
}
In this example, we define a custom macro called f_string
that takes any tokens and passes them directly to the format!
macro. The format!
macro then performs the string interpolation based on the provided tokens.
You can use the f_string
macro to achieve a syntax similar to Python's f-strings, where you enclose the variable name in curly braces directly within the string. However, note that Rust's macro system has different syntax and capabilities compared to Python, so the resulting macro might not provide all the same features or flexibility as Python's f-strings.
Top comments (3)
You can mention that it works with several variables and with custom types ;)
Noice \o/
Oh i found it!
// Usage is simple: just append
_f
to the name of any formatting macroprintln_f!("Hello, {name}!");
But that's not cool like
python print(f“hi {name}”)
Or
c# console.print( $“hi {name}” )