Debug 开发者调试
Debug用于调试输出,紧凑输出:{:?}、美化输出:{:#?}。- 通常自动派生:
#[derive(Debug)] - 自动派生时输出字段名、完整结构信息,也可以手动实现:
impl std::fmt::Debug - 用于:日志记录、单元测试、开发阶段打印变量
- 注意:由于
Debug自动派生时输出包含所有字段,切勿 在Debug输出中包含密码、密钥等敏感信息,或者在手动实现时将其掩码处理。
Display 用户展示
-
Display用于自定义用户输出:{} -
必须手动实现:
impl std::fmt::Display -
输出简洁、友好、正式,旨在让最终用户易读
-
用于:CLI 工具输出、API 响应、错误提示消息
Debug 使用
Debug自动派生
rust
#[derive(Debug)] // 自动实现 Debug
struct User {
id: usize,
username: String,
password: String,
}
fn main() {
let user = User{id:1,username:"xiao".to_string(),password:"abc123".to_string()};
println!("{:?}",user); // 调试输出紧凑模式
println!("{:#?}",user); // 调试输出美化模式
}
程序输出:
bash
# {:?} 调试输出紧凑模式
User { id: 1, username: "xiao", password: "abc123" }
# {:#?} 调试输出美化模式
User {
id: 1,
username: "xiao",
password: "abc123",
}
Debug 手动实现 impl std::fmt::Debug(未区分美化模式)
rust
use std::fmt;
struct User {
id: usize,
username: String,
password: String,
}
impl fmt::Debug for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "User{{id={},username={}}}",self.id, self.username )
}
}
fn main() {
let user = User{id:1,username:"xiao".to_string(),password:"abc123".to_string()};
println!("{:?}",user); // 调试输出紧凑模式
println!("{:#?}",user); // 调试输出美化模式
}
程序输出:
bash
# {:?} 调试输出紧凑模式
User{id=1,username="xiao"}
# {:#?} 调试输出美化模式
User{id=1,username="xiao"}
Debug 手动实现 impl std::fmt::Debug(区分美化模式)
rust
use std::fmt;
struct User {
id: usize,
username: String,
password: String,
}
impl fmt::Debug for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate(){
// 当使用 {:#?} 时,f.alternate() 为 true
write!(f, "User{{\n id={},\n username={}\n}}",self.id, self.username )
}else{
// 当使用 {:?} 时,f.alternate() 为 false
write!(f, "User{{id={},username={}}}",self.id, self.username )
}
}
}
fn main() {
let user = User{id:1,username:"xiao".to_string(),password:"abc123".to_string()};
println!("{:?}",user); // 调试输出紧凑模式
println!("{:#?}",user); // 调试输出美化模式
}
程序输出:
bash
# {:?} 调试输出紧凑模式
User{id=1,username="xiao"}
# {:#?} 调试输出美化模式
User{
id=1,
username="xiao"
}
Display 的使用
rust
use std::fmt;
#[derive(Debug)] // 实现 Display 不影响 Debug 的使用
struct User {
id: usize,
username: String,
password: String,
}
// Display 必须手动实现
impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "您的id:{},您的用户名:{}",self.id, self.username )
}
}
fn main() {
let user = User{id:1,username:"xiao".to_string(),password:"abc123".to_string()};
println!("{:?}",user); // Debug 调试输出紧凑模式
println!("{:#?}",user); // Debug 调试输出美化模式
// 实现 Display 的输出
println!("{}",user);
}
程序输出:
bash
# {:?} Debug 调试输出紧凑模式
User { id: 1, username: "xiao", password: "abc123" }
# {:#?} Debug 调试输出美化模式
User {
id: 1,
username: "xiao",
password: "abc123",
}
# {} Display 的输出
您的id:1,您的用户名:abc123