Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an enum reference to a number?

Tags:

rust

I have an enum:

enum Foo {     Bar = 1, } 

How do I convert a reference to this enum into an integer to be used in math?

fn f(foo: &Foo) {     let f = foo as u8;  // error[E0606]: casting `&Foo` as `u8` is invalid     let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`     let f = *foo as u8; // error[E0507]: cannot move out of borrowed content } 
like image 204
Vitaly Kushner Avatar asked Jul 11 '15 15:07

Vitaly Kushner


People also ask

How do you convert enum to int in Python?

Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can enums contain numbers?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.


1 Answers

*foo as u8 is correct, but you have to implement Copy because otherwise you would leave behind an invalid reference.

#[derive(Copy, Clone)] enum Foo {     Bar = 1, }  fn f(foo: &Foo) -> u8 {     *foo as u8 } 

Since your enum will be a very lightweight object you should pass it around by value anyway, for which you would need Copy as well.

like image 156
A.B. Avatar answered Oct 08 '22 00:10

A.B.