rust - 如何简化重复功能逻辑

标签 rust refactoring program-structure

问题

我想知道是否有一种方法可以改善程序中某些函数的当前结构,因为我觉得有很多不必要的重复发生。

背景

我正在编写一个小型记录器,以便CLI应用程序可以在终端中包含更漂亮的文本。我有几个函数,将一些图标添加到要输出到stdout的图标上,例如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

最佳答案

您可以将same_line更改为line_ending。除了存储true之外,您还可以存储\n并始终使用print!("... {}", ..., &self.line_ending)。我还要添加一个函数pop_line_ending(),该函数返回存储的行结尾并清除它。

关于rust - 如何简化重复功能逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389808/

相关文章:

C - 程序结构(避免全局变量、包含等)

java - 用户定义类的类型转换

testing - 使用 cargo 运行测试时如何忽略示例?

Rust 对迭代器中的引用的引用

rust - 如何记录二进制 Rust crate 项目?

typescript - 在 Visual Studio Code 中提取 TypeScript 方法

iphone - 如何批量编辑/重构 XIB 文件的属性?

c# - 在 Main() 中保持模块化?

string - 如何创建具有字符串成员的 Rust 结构?