面试题答案
一键面试实现思路
- 直接引用数据:为了避免不必要的内存分配和复制,在实现
std::fmt::Display
时,尽量使用对BigData
结构体成员的引用。 - 紧凑二进制格式打印特定子结构:对于特定复杂子结构,编写自定义的二进制格式化函数,将其转换为紧凑且易于理解的二进制格式字符串。
- 利用
write!
宏:使用std::fmt::Write
trait 中的write!
宏来构建输出字符串,这可以减少中间字符串的创建,提高性能。
关键代码片段
use std::fmt;
// 假设 BigData 结构体定义如下
struct BigData {
simple_field: u32,
complex_substruct: ComplexSubstruct,
}
struct ComplexSubstruct {
data: [u8; 4],
}
// 为 ComplexSubstruct 实现自定义二进制格式打印
impl fmt::Display for ComplexSubstruct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut binary_str = String::new();
for byte in self.data.iter() {
for bit in (0..8).rev() {
if byte & (1 << bit) != 0 {
binary_str.push('1');
} else {
binary_str.push('0');
}
}
binary_str.push(' ');
}
write!(f, "{}", binary_str.trim_end())
}
}
// 为 BigData 实现 Display trait
impl fmt::Display for BigData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BigData {{ simple_field: {}, complex_substruct: {} }}",
self.simple_field, self.complex_substruct)
}
}
使用示例
fn main() {
let data = BigData {
simple_field: 42,
complex_substruct: ComplexSubstruct { data: [0x41, 0x42, 0x43, 0x44] },
};
println!("{}", data);
}
上述代码首先定义了 BigData
结构体及其包含的 ComplexSubstruct
结构体。然后分别为 ComplexSubstruct
和 BigData
实现了 fmt::Display
trait。在 ComplexSubstruct
的 fmt
方法中,将字节数组转换为紧凑的二进制格式字符串。在 BigData
的 fmt
方法中,利用 write!
宏构建最终的打印字符串,确保性能优化并按要求格式化输出。