Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding enum's types in Crystal

Tags:

crystal-lang

I am trying to implement the famous Lox language based on Robert Nystrom's book, but in Crystal. Now I stumbled upon the following flaw/error:

I have an enum for OpCodes, with type UInt8:

enum OpCode : UInt8
  OP_RETURN = 1
end

and an array of UInt8's

@code = Pointer(UInt8).malloc( 8 )

But now when I want to assign code[0] = OP_RETURN, even with all possible type conversions I still get the following error message:

Error: can't cast OpCode to UInt8

But I thought OpCode WAS UInt8 as declared.

Any ideas? Really appreciated. I'm just in the baby steps of learning Crystal but so far I'm impressed by this language but there are edge corners where one just needs help.

like image 869
Alectionik Avatar asked Oct 28 '25 06:10

Alectionik


1 Answers

Crystal's enums provide a type safe way to define a list of related magic values. They're not meant to be interchangeable with their underlying value.

Your options are to base your array on the type directly and if really needed to convert on use of the values from the array. Or to convert the enum to the underlying value when assigning to the array. In either case you would do this simply by calling #value on the enum value instance, OpCode::OP_RETURN.value. But I would recommend to try to stay high-level and keep working with the enum instance values directly for as long as possible. Rest assured there's no performance penalty when doing so.

Read more about enums in the language reference: https://crystal-lang.org/reference/1.4/syntax_and_semantics/enum.html

On a side note I can only recommend you strongly to not abuse Pointer as an "array", use the dedicated Array class, Slice if you really need to go lower level or StaticArray when you need value semantics. All of these provide #to_unsafe for use cases where you need to provide a Pointer to a third party library that expects it.

like image 101
Jonne Haß Avatar answered Oct 31 '25 04:10

Jonne Haß



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!