I made a crate which allows you to define custom literals like "hello {name}"f

⚓ Rust    📅 2025-09-21    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 40 days ago. The information described in this article may have changed.

Since literals in Rust can have any suffix, we can use this to create custom literals. Here are some examples

#[culit]
fn main() {
    assert_eq!(100nzusize, NonZeroUsize::new(100).unwrap());
    // COMPILE ERROR!
    // let illegal = 0nzusize;
}
#[culit]
fn main() {
    let name = "bob";
    let age = 23;

    assert_eq!(
        "hi, my name is {name} and I am {age} years old"f,
        format!("hi, my name is {name} and I am {age} years old")
    );
}
#[culit]
fn main() {
    assert_eq!(
        100d + 11h + 8m + 7s,
        Duration::from_secs(100 * 60 * 60 * 24)
        + Duration::from_secs(11 * 60 * 60)
        + Duration::from_secs(8 * 60)
        + Duration::from_secs(7)
    );
}

All of these literals are defined by You, I just export a #[culit] attribute which allows you to use them

1 post - 1 participant

Read full topic

🏷️ Rust_feed