Rust有四種向控制臺輸出的方式,分別為format!(),print!(),println!(),dbg!()。
前三種打印操作定義在std::fmt里面
用法如下:
let a = "myself";
format!("this is {}",&a);
println!("this is {:?}",&a);
println!("this is {}",&a);
print!("this is {}",&a);
dbg!(&a);
[Running: cargo run --message-format=json]
Compiling study v0.1.0 (/home/banapy/projects/study)
Finished dev [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/study`
this is "myself"
this is myself
[src/main.rs:7] &a = "myself"
this is myself[Finished in 0.7s]
std::fmt中包含多種trait來控制文字的顯示,這里面有兩個重要的基本格式類型如下:
-
fmt::Debug使用 {:?} 作標記。格式化文本以便調(diào)試。 -
fmt::Display使用 {} 作標記。以優(yōu)雅和友好的方式來格式文本。
自己實現(xiàn)該trait
對于自定義的結(jié)構(gòu)體,只有它實現(xiàn)以上兩種trait之一時,才能被打印
//#[derive(Debug)]
struct Student {
name: String,
year:u8,
}
impl Student{
fn new(a:&str,b:u8)->Self{
Self{
name:a.to_string(),
year:b,
}
}
}
fn main(){
let x = Student::new("xiaoming",18);
println!("{:?}", &x);
}
此時會報錯
error: src/main.rs:17: `Student` doesn't implement `std::fmt::Debug`
error: src/main.rs:17: `Student` cannot be formatted using `{:?}`
為其實現(xiàn)std::fmt::Debug和std::fmt::Display特性
use std::fmt;
//#[derive(Debug)]
struct Student {
name: String,
year:u8,
}
impl Student{
fn new(a:&str,b:u8)->Self{
Self{
name:a.to_string(),
year:b,
}
}
}
impl fmt::Debug for Student{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Student {{ x: {}, y: {} }}", self.name, self.year)
}
}
impl fmt::Display for Student{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.name, self.year)
}
}
fn main(){
let x = Student::new("xiaoming",18);
println!("{:?}", &x);
}
[Running: cargo run --message-format=json]
Compiling study v0.1.0 (/home/banapy/projects/study)
Finished dev [unoptimized + debuginfo] target(s) in 0.74s
Running `target/debug/study`
Student { x: xiaoming, y: 18 }
(xiaoming, 18)
就是說,當Student實現(xiàn)std::fmt::Debug時,能使用println!("{:?}",x)執(zhí)行打印操作。
把//#[derive(Debug)]的//去掉時能自動為Student實現(xiàn)std::fmt::Debug特性。
神奇吧!這是宏的一種,屬于過程宏中的自定義宏,而println!()為類函數(shù)宏。用戶也能使用關(guān)鍵字macro_rules!自定義宏,這稱為聲明宏。