New crate `docstr!`: Generate multi-line strings from doc comments

⚓ Rust    📅 2025-09-19    👤 surdeus    👁️ 9      

surdeus

Warning

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

I made a new crate that has a novel approach to writing multi-line string literals:

use docstr::docstr;

let hello_world_in_c: &'static str = docstr!(
    /// #include <stdio.h>
    ///
    /// int main(int argc, char **argv) {
    ///     printf("hello world\n");
    ///     return 0;
    /// }
);

assert_eq!(hello_world_in_c, r#"#include <stdio.h>

int main(int argc, char **argv) {
    printf("hello world\n");
    return 0;
}"#)

It can compose with any macro that uses format_args!():

use docstr::docstr;

let age = 21;
let name = "Bob";
let colors = ["red", "green", "blue"];

let greeting: String = docstr!(format!
                             //^^^^^^^ the generated string is passed to `format!`
                             //        as the 1st argument
    /// Hello, my name is {name}.
    /// I am {age} years old!
    ///
    /// My favorite color is: {}

    // anything after the doc comments is passed directly at the end
    colors[1]
);
//^ above expands to: format!("...", colors[1])

assert_eq!(greeting, "Hello, my name is Bob.\nI am 21 years old!\n\nMy favorite color is: green");

GitHub: GitHub - nik-rev/docstr: Ergonomic multi-line string literals

1 post - 1 participant

Read full topic

🏷️ Rust_feed