格式化输出
格式化输出函数
Rust宏 | 含义 | 对应c/c++函数 |
---|---|---|
print! | 将格式化文本输出到标准输出 | print, cout |
println! | 将格式化文本输出到标准输出,带换行 | print格式加\n , cout加std::endl |
eprint | 将格式化文本输出到标准错误 | print,cerr |
eprintln! | 将格式化文本输出到标准错误,带换行 | print格式加\n , cerr加std::endl |
format! | 将格式化文本输出到 String 字符串 | sprint,stringstream |
例子
{} 为占位符,等同于c中%d,%f的%。
fn main() {
println!(); // 只换行
println!("hello");
let w = "world";
println!("hello {}", w);
let h = "hello";
let hw = format!("{} {}", h, w);
println!("{}", hw);
}
输出
hello
hello world
hello world
占位符 {} 和 {:?}
占位符 | 用途 |
---|---|
{} | 实现了 std::fmt::Display 特征的类型才能使用,用于自定义显示输出 |
{:?} | 实现了 std::fmt::Debug 特征的类型才能使用,用于调试 |
大多数 Rust 类型都实现了 Debug 特征,结构体,枚举需要实现Debug 特征。
基础类型都实现了Display 特征,对于vector,tuple,结构体,枚举需要自己实现Display 特征。
例子
fn main() {
let n:u16 = 100;
println!("{}", n);
println!("{:?}", n);
let w = "world";
println!("hello {}", w);
println!("hello {:?}", w);
let b:bool = false;
println!("bool: {}", b);
println!("bool: {:?}", b);
let v = vec![1, 2, 3];
//println!("vector: {}", v); // 默认不支持
println!("vector: {:?}", v);
let t = (100, "string", 1.0);
//println!("vector: {}", t); // 默认不支持
println!("vector: {:?}", t);
}
输出
100
100
hello world
hello "world"
bool: false
bool: false
vector: [1, 2, 3]
vector: (100, "string", 1.0)
支持Debug特征
#[derive(Debug)] 通过增加该属性宏,自动为结构体,枚举实现了Debug特征。
dbg! 也可以打印,用于调试:
- dbg!打印值连同宏调用的源位置以及表达式的源代码。
- dbg! 输出到stderr。
- 不要依赖此宏打印,打印值可能会在未来发生变化。
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 50,
height: 80
};
dbg!(&rect1);
println!("{:?}", rect1);
}
支持Display 特征
use std::fmt;
struct Rectangle {
width: u32,
height: u32,
}
impl fmt::Display for Rectangle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Display: ({}, {})", self.width, self.height)
}
}
fn main() {
let rect1 = Rectangle {
width: 50,
height: 80
};
println!("{}", rect1);
}
更多格式化格式,参考标准库文档
std::fmt