Parsing strings to enum fields

Hellope,

while parsing a config file, I came across the problem of verifying if a string (I parsed from the config) is a valid enum field. Thanks to reflect.enum_field_names() I can easily get a slice of the valid fields, but I cannot find any kind of contains() function.

Do I have to implement that myself? Or is there a nicer way of making sure that a string is an enum field value?

You could do…

MyEnum :: enum {
	Zero,
	One,
	Two,
}

ok: bool

// exists
_, ok = reflect.enum_from_name(MyEnum, "One")
fmt.println(ok)

// ! exists
_, ok = reflect.enum_from_name(MyEnum, "Three")
fmt.println(ok)
2 Likes

Also, common string related procedures like contains, index, split, join, etc. can be found in the core strings package.

https://pkg.odin-lang.org/core/slice/#linear_search

Thanks, everyone!

reflect.enum_from_name() was exactly what I was looking for. I ended up with

waypoint.type = reflect.enum_from_name(WaypointType, typeString) or_return

slice.linear_search() will also be helpful in the future. Being new to Odin, it’s still difficult to find out what the things I’m looking for are called exactly, but so far I eventually found everything I need. Coming from C, I really like the language.

If you are using VSCode or VSCodium, install the “Odin Language” extension by DanielGavin. Or if using Helix, Vim, or other editor, install ols. The ols page has directrions for several editors.

Once you have a language server setup, you could allow auto-complete to tell you what is possible. For example, in VSCodium (or VSCode), if I just type “reflect.enum”, I’ll get a popup list of all possible objects that have the words “reflect” and “enum” in them, so I can see all my options. Very helpful when trying to find the right things.

There’s also an odin language plugin for jetbrains IDEs as well.