LogoDuyệtSr. Data Engineer
HomeAboutPhotosInsightsCV

Footer

Logo

Resources

  • Rust Tiếng Việt
  • /archives
  • /series
  • /tags
  • Status

me@duyet.net

  • About
  • LinkedIn
  • Resume
  • Projects

© 2026 duyet.net | Sr. Data Engineer

Rust: Format Strings in 1.58

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

Bản cập nhật Rust 1.58.0 vừa bổ sung một số tính năng mình thấy khá hay về format string.

Nó cho phép bạn đặt variables bên ngoài scope vào string format bằng cách sử dụng {ident} trong format string.

let x = "world";
println!("Hello {x}!");

// Hello world!

Một ví dụ với debug output:

let items = vec![10, 20, 30];
println!("{items:?}")
// [10, 20, 30]

println!("{items:#?}")
// [
//    10,
//    20,
//    30,
// ]

Bạn cũng có thể format string với minimum width, cú pháp là :[width]

let items = ["these", "words", "are", "different", "sizes"];
let column1 = "item";
let column2 = "iter";
println!("{column1:10}| {column2}");
println!("----------------");
for (i, item) in items.iter().enumerate() {
    println!("{item:10}: {i}");
}

// item      | iter
// ----------------
// these     : 0
// words     : 1
// are       : 2
// different : 3
// sizes     : 4

Canh giữa:

println!("----------------");
for (i, item) in items.iter().enumerate() {
    println!("{item:^10}: {i}");
}

// ----------------
//    these   : 0
//    words   : 1
//     are    : 2
//  different : 3
//    sizes   : 4

Canh phải:

println!("----------------");
for (i, item) in items.iter().enumerate() {
    println!("{item:>10}: {i}");
}

// ----------------
//      these: 0
//      words: 1
//        are: 2
//  different: 3
//      sizes: 4

Sử dụng một biến i32 thì chỉ cần đặt $ phía sau variable name.


let spaces = 10;
println!("hello {x:spaces$}!");

// "hello world     !"

Điền vào khoảng trống với bất kì ký tự nào

println!("right aligned: hello{x:->7}!");
println!("left aligned: hello{x:-<7}!");
println!("center aligned: hello{x:-^7}!");

// right aligned: hello--world!
// left aligned: helloworld--!
// center aligned: hello-world-!

Để escape dấu ngoặc

println!("Sometimes I need to print {{ or }} too!")
// Sometimes I need to print { or } too!

References

  • Format Strings in Rust 1.58
  • Announcing Rust 1.58.0
Jan 18, 2022·4 years ago
|Rust|
RustVietnameseRust Tiếng Việt
|Edit|
On this page
  • References
On this page
  • References