如何指定Rust中的枚举的表示类型与C ++接口? [英] How to specify the representation type for an enum in Rust to interface with C++?

查看:203
本文介绍了如何指定Rust中的枚举的表示类型与C ++接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以在Rust中使用显式表示类型进行C ++风格的枚举?例如:

 枚举类号:int16_t {
零,一,二,三,四,五,六,七,八,九
};

如果没有,是否有另一种方式可以组织这样的变量?我正在与外部库进行连接,因此指定类型很重要。我知道我可以做:

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

但在我看来,这引入了很多冗余;






请注意,此问题与是否可以在Rust中包含C枚举?,因为它是关于包装C ++,而不是包装C。

解决方案

您可以指定枚举的表示。

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

Is there a way I can make a C++ style enumeration with explicit representation type in Rust? Example:

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

If not, is there another way I can organize variables like that? I am interfacing with an external library, so specifying the type is important. I know I could just do:

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

But that introduces a lot of redundancy, in my opinion;


Note this question is not a duplicate of Is it possible to wrap C enums in Rust? as it is about wrapping C++, not wrapping C.

解决方案

You can specify a representation for the enum.

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

这篇关于如何指定Rust中的枚举的表示类型与C ++接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆