相关疑难解决方法(0)

将枚举作为字符串

我有一个有许多价值观的枚举

enum Foo {
  Bar = 0x00,
  Baz = 0x01,
  Qux = 0x02,
  ...
  Quux = 0xFF
}
Run Code Online (Sandbox Code Playgroud)

有时我想将其中一个值的名称写入流中.我可以得出Debug

writer.write(format!("I am {:?}", Foo::Quux).as_bytes())
Run Code Online (Sandbox Code Playgroud)

这将输出例如I am Quux.那很好,除了那个

  • 我想为面向用户的输出执行此操作,因此Debug不合适
  • 将枚举作为字符串(而不是直接写入流)非常有用,因为我可以将其长度合并到我想要做的一些不稳定的格式计算中.

实现这一目标的最佳方法是什么?

rust

24
推荐指数
2
解决办法
1万
查看次数

如何在枚举中使用字符串值并避免“预期的`isize`,找到的`&str`”?

我正在尝试使用,enum但我需要将字符串值保存在数据库、Redis 等中。

pub enum Place {
  Square = "1",
  House = "2",
  Office = "3",
  // and so on... Garage = "4",
}
Run Code Online (Sandbox Code Playgroud)

但编译器抛出:

error[E0308]: mismatched types
  |
3 |     Square = "1",
  |             ^^^ expected `isize`, found `&str`

error[E0308]: mismatched types
  |
4 |     House = "2",
  |            ^^^ expected `isize`, found `&str`

error[E0308]: mismatched types
  |
5 |     Office = "3",
  |            ^^^ expected `isize`, found `&str`

For more information about this error, try `rustc --explain …
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
1
解决办法
830
查看次数

标签 统计

rust ×2