Rust: indoc

RustAug 6, 20225 min read

Note: This post is over 5 years old. The information may be outdated.

Chuỗi bài viết Rust Tiếng Việt là một trong những nội dung nằm trong sách Rust Tiếng Việt

indoc là một crate nhỏ nhưng hữu ích giúp canh lề (indented documents). indoc!() macro nhận multiline string và un-indents lúc compile time, xoá tất cả khoảng trắng đầu tiên trên cách dòng dựa theo dòng đầu tiên.

File: Cargo.toml

[dependencies]
indoc = "1"

Ví dụ:

use indoc::indoc;

fn main() {
    let testing = indoc! {"
        def hello():
            print('Hello, world!')

        hello()
    "};

    let expected = "def hello():\n    print('Hello, world!')\n\nhello()\n";
    assert_eq!(testing, expected);
}

indoc cũng hoạt động với raw string r# ... # và byte string b" ... ".

References