Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
Rust: Formatted print
Dùng macro println
Ví dụ
fn main() {
let title = "Kipa";
println!("{}log", title);
}
Chúng ta có thể đưa trực tiếp biến title
vào trong macro println
fn main() {
println!("{title}log", title="Kipa");
}
Lazy print for debug
Chúng ta có thể dùng macro println
để debug 1 struct trong Rust
fn main() {
let vectos = vec![1, 2, 3, 4];
println!("{:?}", vectors);
}
Output => [1, 2, 3, 4]
Format {:?}
dùng cho traitDebug
Tuy nhiên format {:?}
chỉ dùng được cho những struct implement trait Debug
impl Debug<T> for Vec<T>
Nếu những stuct còn lại muốn áp dùng được dạng println
thì phải làm thao, đơn giản nhất là thêm derive(Debug)
trước struct đó
#[dervie(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 6, y: 9 };
println!("{:?}", point);
}
Output => Point { x: 6, y: 9 }
Nếu không muốn dùng derive(Debug)
chúng ta có thể implement trait Debug
use std::fmt::{Debug, Formatter, Result};
struct Point {
x: i32,
y: i32
}
impl Debug for Point {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "CustomPoint {{ x: {}, y: {} }}", self.x, self.y)
}
}
fn main() {
let point = Point { x: 6, y: 9 };
println!("{:?}", point);
}
Output => CustomPoint { x: 6, y: 9 }
Lưu ý: hàm fmt
chúng ta cần trả về giá trị nên không có ;
đối với macro write
.
Vậy struct Point
ở trên khi ta dùng println!
bình thường nó sẽ như thế nào ?
struct Point {
x: i32,
y: i32
}
fn main() {
let point = Point { x: 10, y: 10 };
println!("{}", point);
}
Output => error: the trait bound `Point: std::fmt::Display` is not satisfied
Điều này có nghĩa là chúng ta cần implement trait Display
cho struct Point
use std::fmt::{Debug, Display, Formatter, Result};
struct Point {
x: i32,
y: i32
}
impl Debug for Point {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "CustomPoint {{ x: {}, y: {} }}", self.x, self.y)
}
}
// Implement trait Display for Point
impl Display for Point {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "DisplayPoint {{ x: {}, y: {} }}", self.x, self.y)
}
}
fn main() {
let point = Point { x: 6, y: 9 };
println!("{}", point);
}
Output => DisplayPoint { x: 6, y: 9 }






