[教程]print

Rust有四種向控制臺輸出的方式,分別為format!(),print!(),println!(),dbg!()。
前三種打印操作定義在std::fmt里面

  • format!:將格式化文本寫到字符串(String)。(譯注: 字符串是返回值不是參數(shù)。)
  • print!:與 format!類似,但將文本輸出到控制臺。
  • println!: 與 print!類似,但輸出結(jié)果追加一個換行符。
  • dbg!用于調(diào)試,輸出文件名+行號+表達式:[src/main.rs:7] &a = "myself"
    這里的!代表println!()是個宏,rust中的宏不是c中簡單的文本替換,而是更強大的工具,在以后的文章中有專門介紹。

用法如下:

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::Debugstd::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!自定義宏,這稱為聲明宏。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容