DEV Community

Cover image for Rust: Embrace the Pythonic Flair with F-String Style!
Santhosh Balasa
Santhosh Balasa

Posted on • Edited on

Rust: Embrace the Pythonic Flair with F-String Style!

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);
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
pgradot profile image
Pierre Gradot

You can mention that it works with several variables and with custom types ;)

use std::fmt;

macro_rules! f_string {
    ($($tokens:tt)*) => {
        format!($($tokens)*)
    };
}

struct MyStruct {
    value: u32,
}

impl fmt::Display for MyStruct {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Mystruct({})", self.value)
    }
}

fn main() {
    let value = "42";
    let message = "some message";
    let ms = MyStruct{value:66};
    println!("{}", f_string!("{value} => {message} => {ms}"));
}
Enter fullscreen mode Exit fullscreen mode

Noice \o/

Collapse
 
rc2168st profile image
rc2168st

Oh i found it!

// Usage is simple: just append _f to the name of any formatting macro
println_f!("Hello, {name}!");

Collapse
 
rc2168st profile image
rc2168st

But that's not cool like
python print(fโ€œhi {name}โ€)
Or
c# console.print( $โ€œhi {name}โ€ )