2016-12-15 51 views
3

此代碼的工作:在Rust中,println中「{}」和「{:?}」有什麼區別!?

let x = Some(2); 
println!("{:?}", x); 

但這並不:

let x = Some(2); 
println!("{}", x); 
 
5 | println!("{}", x); 
    |    ^trait `std::option::Option: std::fmt::Display` not satisfied 
    | 
    = note: `std::option::Option` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string 
    = note: required by `std::fmt::Display::fmt` 

爲什麼?在這種情況下,:?是什麼?

回答

4

{:?},或者,特別是?,是Debug特徵所使用的佔位符。如果類型不執行Debug,則在格式字符串中使用{:?}中斷。

例如:

struct MyType { 
    the_field: u32 
} 

fn main() { 
    let instance = MyType { the_field: 5000 }; 
    println!("{:?}", instance); 
} 

..fails用:

error[E0277]: the trait bound `MyType: std::fmt::Debug` is not satisfied 

Implementing Debug though, fixes that

#[derive(Debug)] 
struct MyType { 
    the_field: u32 
} 

fn main() { 
    let instance = MyType { the_field: 5000 }; 
    println!("{:?}", instance); 
} 

,其輸出:MyType { the_field: 5000 }

你可以看到這些佔位符/運營商in the documentation的列表。

相關問題