Rust pattern: Display adapter

栏目: IT技术 · 发布时间: 4年前

内容简介:Sometimes, you want to display a value in a specific way. Convert aLet's start with what anyone would do in most languages: Write a function that returns a string:The first example converts a camel-case identifier to a lower-snake-case one:

Sometimes, you want to display a value in a specific way. Convert a String to a different format, display a i32 in a particular way. What is the most ergonomic way to do that in Rust?

The obvious solution

Let's start with what anyone would do in most languages: Write a function that returns a string:

The first example converts a camel-case identifier to a lower-snake-case one:

fn to_snake_case(ident: &str) -> String {
    let mut result = String::new();

    let mut first = true;
    for c in ident.chars() {
        if c.is_uppercase() {
            if !first {
                result.push('_');
            }

            for c in c.to_lowercase() {
                result.push(c);
            }
        } else {
            result.push(c);
        }

        first = false;
    }

    result
}

assert_eq!(to_snake_case("SomeLongIdentifier"), "some_long_identifier");

The second example converts an i32 to a string that says " N above zero" for positive N , " N below zero" for negative N and "zero" if the value is 0.

fn to_wordy_number(n: i32) -> String {
    match n {
        n if n < 0 => format!("{} below zero", -n),
        n if n > 0 => format!("{} above zero", n),
        0 => "zero".into(),
    }
}

assert_eq!(to_wordy_number(-5), "5 below zero");
assert_eq!(to_wordy_number(5), "5 above zero");
assert_eq!(to_wordy_number(0), "zero");

What's wrong with this pattern? The purpose of such conversions is usually to use the result in a larger string, or for writing it to a file or the standard output. You're probably doing unnecessary allocations for intermediate strings, only to make them parts of something bigger and drop them. And this has no chance of working in no_std without liballoc.

A more rusty solution: Display adapters

I am sure I am not the first one to come up with this pattern, as it's rather obvious. Still, I could not find anyone discussing it explicitly.

By implementing the Display trait on a tuple struct with a single pub field, we can create an adapter that transforms how a type is printed. Let us transform our examples:

struct SnakeCase<'a>(&'a str);

impl<'a> Display for SnakeCase<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for c in self.0.chars() {
            if c.is_uppercase() {
                if !first {
                    fmt.write_char('_')?;
                }

                write!(fmt, "{}", c.to_lowercase())?;
            } else {
                fmt.write_char(c)?;
            }

            first = false;
        }

        Ok(())
    }
}

assert_eq!(
    SnakeCase("SomeLongIdentifier").to_string(),
    "some_long_identifier"
);
let identifier = format!("{}_mut", SnakeCase("SomeLongIdentifier"));
struct WordyNumber(i32);

impl Display for WordyNumber {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            n if n < 0 => write!(fmt, "{} below zero", -n),
            n if n > 0 => write!(fmt, "{} above zero", n),
            _ => fmt.write_str("zero"),
        }
    }
}

assert_eq!(WordyNumber(-5).to_string(), "5 below zero");
assert_eq!(WordyNumber(5).to_string(), "5 above zero");
assert_eq!(WordyNumber(0).to_string(), "zero");
println!("The temperature is {}.", WordyNumber(5));

This has several advantages over creating a string:

  • You only allocate what you really need by delaying formatting (or you might not allocate at all).
  • There is no runtime overhead from creating or using the adapter.
  • It works with everything that supports Rust's formatting machinery (including ToString::to_string() , println! , format! and friends).
  • It works with no_std.

I want to encourage everyone who currently publishes custom string conversion functions to use this pattern instead.

If you think any part of this article is confusing, misleading or even incorrect, please file an issue or open a pull request on GitHub.

Thanks for reading!


以上所述就是小编给大家介绍的《Rust pattern: Display adapter》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

奥美的数字营销观点

奥美的数字营销观点

[美] 肯特·沃泰姆、[美] 伊恩·芬威克 / 台湾奥美互动营销公司 / 中信出版社 / 2009-6 / 45.00元

目前,媒体的数字化给营销人带来了重大影响。新媒体世界具有多重特性,它赋予企业大量机会,同时也带来挑战。营销人有了数量空前的方式来与消费者互动。然而,许多人面对变革的速度感到压力巨大,而且不知道该如何完全发挥这些新选择所带来的优势。 本书为读者提供了如何运用主要数字媒体渠道的方法;随附了领先的营销人如何在工作中有效运用这些渠道的最佳案例;提供了数字营销的十二个基本原则;协助数字营销人了解什么是......一起来看看 《奥美的数字营销观点》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具