|
So I have a small question, are there any advantages to using docstr instead of const S: &'static str = docstr!(
/// &'static str content
/// Other content
);Is the exact same as this one: const S: &'static str = r#"&'static str content
Other content
"#;and passing macros is also unaffected: let file_name = "file.rs";
docstr!(format!
/// [INFO] current status:
/// Reading file: {}
file_name
);Is the same as: let file_name = "file.rs";
format!(r#"[INFO] current status:
Reading file: {}"#, file_name);So what's the difference? |
Replies: 1 comment
|
Embedding formatted text in Rust's string literals forces us to make a choice:
Sacrifice readability of the outputIn order to print the following: create table student(
id int primary key,
name text
)The initial attempt might look as follows: fn main() {
println!("
create table student(
id int primary key,
name text
)
");
}Which outputs (using ^
^········create table student(
^············id int primary key,
^············name text
^········)
^····
^The output is formatted in an unconventional way, containing excessive leading indentation. The alternative allows for a sane output, but at the cost of making the code less readable: Sacrifice readability of the source codeIn order for the output to be more sensible, we must sacrifice readability of the source code: fn main() {
println!(
"\
create table student(
id int primary key,
name text
)");
}The above example would output the expected: create table student(
id int primary key,
name text
)But the improvement in output comes at a cost:
As you can see, we have to choose one or the other. In either case we have to give something up. Another way to format the above would be the following: fn main() {
println!(concat!(
"create table student(\n",
" id int primary key,\n",
" name text,\n",
")\n",
));
}The above:
However, it looks very noisy.
Sometimes, we are forced into the first option - sacrificing readability of the source. In some cases, producing excessive whitespace will change meaning of the output. Consider whitespace-sensitive languages such as Python or Haskell, or content which is meant to be read by people like generated Markdown - here we can't make a sacrifice on readabilty of the output - so our source code must become harder to understand. But, what if we could have the best of both worlds? That's what fn main() {
docstr!(println!
/// create table student(
/// id int primary key,
/// name text
/// )
);
} |
Embedding formatted text in Rust's string literals forces us to make a choice:
Sacrifice readability of the output
In order to print the following:
The initial attempt might look as follows:
Which outputs (using
^to mark the beginning of a line, and·to mark a leading space):The output is formatted in an unconven…