问题
我想知道是否有办法改进我程序中某些函数的当前结构,因为我觉得发生了大量不需要的重复。
背景
我正在编写一个小型记录器,以便 CLI 应用程序可以在终端中拥有更漂亮的文本。我有几个函数可以向标准输出添加一些图标,例如success()
,它需要一条消息并向其添加一个绿色复选标记图标,与 等相同error()
。warn()
它们都可以在末尾添加换行符或忽略它取决于用户是否same()
在它之前调用过。
目前他们使用下面定义的三个函数来决定是否添加换行符,以及是否添加时间戳。
代码
/// Outputs to stdout with an icon
fn output<T: Display>(&mut self, message: T, icon: LogIcon) {
let timestamp = self.timestamp();
if self.same_line {
print!("{} {}{}", icon, timestamp, message);
} else {
println!("{} {}{}", icon, timestamp, message);
}
self.same_line = false;
}
/// Outputs to stderr with an icon
fn output_error<T: Display>(&mut self, message: T, icon: LogIcon) {
let timestamp = self.timestamp();
if self.same_line {
eprint!("{} {}{}", icon, timestamp, message);
} else {
eprintln!("{} {}{}", icon, timestamp, message);
}
self.same_line = false;
}
/// Outputs to stdout normally
fn output_normal<T: Display>(&mut self, message: T) {
let timestamp = self.timestamp();
if self.same_line {
print!("{}{}", timestamp, message);
} else {
println!("{}{}", timestamp, message);
}
self.same_line = false;
}
这是该success
函数目前如何使用输出函数的方式:
pub fn success<T: Display>(&mut self, message: T) {
self.output(message, LogIcon::CheckMark);
}
这同样适用于所有其他功能,它们要么输出到stderr
要么stdout
。