【问题标题】:How to specify the representation type for an enum in Rust to interface with C++?如何在 Rust 中指定枚举的表示类型以与 C++ 交互?
【发布时间】:2014-10-19 20:49:00
【问题描述】:

有没有一种方法可以在 Rust 中创建具有显式表示类型的 C++ 样式枚举?示例:

enum class Number: int16_t {
    Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine
};

如果没有,还有其他方法可以像这样组织变量吗?我正在与外部库交互,因此指定类型很重要。我知道我可以这样做:

type Number = int16_t;
let One: Number = 1;
let Two: Number = 2;
let Three: Number = 3;

但在我看来,这会带来很多冗余;


请注意,此问题与 Is it possible to wrap C enums in Rust? 不是重复的,因为它是关于包装 C++,而不是包装 C。

【问题讨论】:

  • @fimor 这个问题是关于 C 风格的枚举,它与 C++ 的不同。
  • 啊,还好你更新了问题:)
  • @JeroenBollen,注意到您从标题中删除了“连接 C++ 时”,这个问题是关于连接 C++ 的吗?否则,它看起来就像“可能在 Rust 中包装 C 枚举?”的副本?
  • @ideasman42 我回滚了您对 OP 没有任何贡献的多余编辑,但标题中的 C++ 是合理的。

标签: enums rust


【解决方案1】:

您可以指定枚举的表示形式。

#[repr(i16)]
enum Foo {
    One = 1,
    Two = 2,
}

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多