一、简介1、Debug开发者调试Debug用于调试输出紧凑输出{:?}、美化输出{:#?}。通常自动派生#[derive(Debug)]自动派生时输出字段名、完整结构信息也可以手动实现impl std::fmt::Debug用于日志记录、单元测试、开发阶段打印变量注意由于Debug自动派生时输出包含所有字段‌切勿‌在Debug输出中包含密码、密钥等敏感信息或者在手动实现时将其掩码处理。2、Display用户展示Display用于自定义用户输出{}必须手动实现impl std::fmt::Display输出简洁、友好、正式旨在让最终用户易读用于CLI 工具输出、API 响应、错误提示消息二、Debug使用1、Debug自动派生#[derive(Debug)]// 自动实现 DebugstructUser{id:usize,username:String,password:String,}fnmain(){letuserUser{id:1,username:xiao.to_string(),password:abc123.to_string()};println!({:?},user);// 调试输出紧凑模式println!({:#?},user);// 调试输出美化模式}程序输出# {:?} 调试输出紧凑模式User{id:1, username:xiao, password:abc123}# {:#?} 调试输出美化模式User{id:1, username:xiao, password:abc123,}2、Debug手动实现impl std::fmt::Debug未区分美化模式usestd::fmt;structUser{id:usize,username:String,password:String,}implfmt::DebugforUser{fnfmt(self,f:mutfmt::Formatter_)-fmt::Result{write!(f,User{{id{},username{}}},self.id,self.username)}}fnmain(){letuserUser{id:1,username:xiao.to_string(),password:abc123.to_string()};println!({:?},user);// 调试输出紧凑模式println!({:#?},user);// 调试输出美化模式}程序输出# {:?} 调试输出紧凑模式User{id1,usernamexiao}# {:#?} 调试输出美化模式User{id1,usernamexiao}3、Debug手动实现impl std::fmt::Debug区分美化模式usestd::fmt;structUser{id:usize,username:String,password:String,}implfmt::DebugforUser{fnfmt(self,f:mutfmt::Formatter_)-fmt::Result{iff.alternate(){// 当使用 {:#?} 时f.alternate() 为 truewrite!(f,User{{\n id{},\n username{}\n}},self.id,self.username)}else{// 当使用 {:?} 时f.alternate() 为 falsewrite!(f,User{{id{},username{}}},self.id,self.username)}}}fnmain(){letuserUser{id:1,username:xiao.to_string(),password:abc123.to_string()};println!({:?},user);// 调试输出紧凑模式println!({:#?},user);// 调试输出美化模式}程序输出# {:?} 调试输出紧凑模式User{id1,usernamexiao}# {:#?} 调试输出美化模式User{id1,usernamexiao}三、Display的使用usestd::fmt;#[derive(Debug)]// 实现 Display 不影响 Debug 的使用structUser{id:usize,username:String,password:String,}// Display 必须手动实现implfmt::DisplayforUser{fnfmt(self,f:mutfmt::Formatter_)-fmt::Result{write!(f,您的id{}您的用户名{},self.id,self.username)}}fnmain(){letuserUser{id:1,username:xiao.to_string(),password:abc123.to_string()};println!({:?},user);// Debug 调试输出紧凑模式println!({:#?},user);// Debug 调试输出美化模式// 实现 Display 的输出println!({},user);}程序输出# {:?} Debug 调试输出紧凑模式User{id:1, username:xiao, password:abc123}# {:#?} Debug 调试输出美化模式User{id:1, username:xiao, password:abc123,}# {} Display 的输出您的id1您的用户名abc123四、.to_string()实现了Display的类型转换为String只要实现了Display trait的类型就可以用.to_string()转换为字符串类型。letshello;lets1s.to_string();// str 转 Stringleta25;lets2a.to_string();// int 转 Stringletbfalse;lets3b.to_string();// boole 转 String// 自定义结构体structPerson{name:String,age:i32,}// 自定义结构体实现 Displayimplfmt::DisplayforPerson{fnfmt(self,f:mutfmt::Formatter)-fmt::Result{write!(f,({}, {}),self.name,self.age)}}letpPerson{name:String::from(xx),age:23};lets4p.to_string();// 自定义结构体转 String