乐闻世界logo
搜索文章和话题

How can I create enums with constant values in Rust?

1个答案

1

Creating an enumeration with constant values in Rust typically involves assigning a fixed integer value to each variant of the enum. This type of enumeration is common in other programming languages, such as enums in C or C++. In Rust, this can be achieved by using the repr attribute and explicitly assigning values to each variant. Here is a concrete example:

rust
// Specify the integer type used for the underlying storage of the enumeration #[repr(i32)] enum StatusCode { Success = 200, NotFound = 404, InternalServerError = 500, } fn main() { // Access the numeric values directly via the enum variants println!("Success code: {}", StatusCode::Success as i32); println!("Not Found code: {}", StatusCode::NotFound as i32); println!("Internal Server Error code: {}", StatusCode::InternalServerError as i32); }

In this example:

  • The #[repr(i32)] attribute instructs the compiler to store the enumeration values using i32.
  • The StatusCode enum has three variants, each assigned a fixed i32 value.
  • Within the main function, type conversion (e.g., StatusCode::Success as i32) allows direct retrieval of the integer value corresponding to each variant.

This approach ensures a deterministic memory representation for the enumeration, which is particularly valuable when interfacing with other languages or systems, such as in scenarios requiring binary compatibility with FFI (Foreign Function Interface).

2024年8月7日 17:09 回复

你的答案