Sorry for the noobish question. I want to understand how using the enums like in C/C++
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
enum country {ITALY, GERMANY, PORTUGAL};
string capital[] = {"Rome", "Berlin", "Lisbon"};
cout<<capital[ITALY];
}
prints "Rome" as expected
type country = enum
ITALY=int(0),
GERMANY=int(1),
PORTUGAL=int(2)
var capital:array = ["Rome", "Berlin", "Lisbon"]
echo capital[ITALY] # error, "ITALY" is not equal to 0 !
The debugger prints a type mismatch. The only solution is to call ord() function but the enum as declared as integers. Thank you in advance for your indulgence.No, arrays can use enums as the index type (and I use this feature all the time):
type country = enum
ITALY,
GERMANY,
PORTUGAL
var capital: array[country, string] = ["Rome", "Berlin", "Lisbon"]
echo capital[ITALY]
Thanks for the help Araq.
The Nim enum behaves differently so I think this code reproduces better the Cpp code behaviour.
# I wonder if it's a good practise
const
ITALY = 0
GERMANY = 1
PORTUGAL = 2
var capital: array = ["Rome", "Berlin", "Lisbon"]
echo capital[PORTUGAL]
Sorry for these snippets full of unused variables ;)
If you'll add a type cast in inddexing, your snippet will work (either of them):
echo capital[ITALY.int]
And Byou can omit type in variable declaration altogether:
var capital = ["Rome", "Berlin", "Lisbon"]
But if the point is to just use explicit values for enum items, then you can add them to Araq's snippet. Then you don't need type casts using the variable.