Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to an enum value

Tags:

go

I have the following code:

type ActorState int

const (
    Unverified ActorState = 1 + iota
    Verified
    Banned
)

And I want to do this in my implementation.

i := 1
a : ActorState 
a = ActorState(i)

But I get the error, Cannot convert expression of type int, error to type ActorState.

How do I convert it then?

like image 945
Geert Van Laethem Avatar asked Oct 27 '17 11:10

Geert Van Laethem


People also ask

How do I convert an int to enum?

Use the Enum. ToObject() method to convert integers to enum members, as shown below.

Can we give integer in enum?

No, we can have only strings as elements in an enumeration.

Can numbers be enums?

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.

How do I find the enum of a number?

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 we assign value to enum in C?

We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.


1 Answers

Your syntax is wrong, you mean

i := 1
a := ActorState(i)

or

i := 1
var a = ActorState(i)

or

i := 1
var a ActorState
a = ActorState(i)
like image 114
gonutz Avatar answered Sep 18 '22 07:09

gonutz