{}
,{:?}
,{:#?}
println!("Hello"); // => Hello
println!("Hello, {}!", "Rust"); // => Hello, Rust!
println!("The number is {}", 1); // => The number is 1
println!("{:?}", (3, 4)); // => (3, 4)
println!("{val}", val = 4); // => 4
println!("{} {}", 1, 2); // => 1 2
println!("{:04}", 42); // => 0042 (带前导零)
{}
适用于实现了std::fmt::Display
特征的类型。{:?}
适用于实现了std::fmt::Debug
特征的类型。
Display
特征
let v = vec![1, 2, 3];
let p = Person {
name: "sunface".to_string(),
age: 18,
};
println!("{}, {}", v, p);
无法过编,因为没有实现 Display
特征,也无法像派生 Debug
一样派生 Display
,解决方法:
- 使用
{:?}
或{:#?}
。 - 为自定义类型实现
Display
。 - 使用
newtype
为外部类型实现Display
。
{:#?}
的输出格式更优雅:
[1, 2, 3] // {:?}
[
1,
2,
3,
] // {:#?}
为自定义类型实现 Display
:
struct Person {
name: String,
age: u8,
}
use std::fmt;
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "name={}, age={}", self.name, self.age)
}
}
fn main() {
let p = Person {
name: "sunface".to_string(),
age: 18,
};
println!("{}", p);
}
为外部类型实现 Display
:
struct Array(Vec<i32>);
use std::fmt;
impl fmt::Display for Array {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "arr={:?}", self.0)
}
}
fn main() {
let arr = Array(vec![1, 2, 3]);
println!("{}", arr);
}
位置参数
println!("{}{}", 1, 2); // => 12
println!("{1}{0}", 1, 2); // => 21
println!("{0}, this is {1}. {1}, this is {0}.", "Alice", "Bob"); // => Alice, this is Bob. Bob, this is Alice.
println!("{1}{}{0}{}", 1, 2); // => 2112
具名参数
println!("{argument}", argument = "test"); // => test
println!("{n} {}", 1, n = 2); // => 2 1
println!("{a} {c} {b}", a = "a", b = 'b', c = 3); // => a 3 b
格式化参数
let v = 3.1415926;
println!("{:.2}", v); // Display => 3.14
println!("{:.2?}", v); // Debug => 3.14