See the following code:
const
md_extension = [".md", ".markdown"]
proc test(ext: string) =
echo "Testing for ", ext
case ext
of ".txt", md_extension:
echo "Found!"
else:
echo "Not found!"
when isMainModule:
test(".something")
test(".markdown")
It won't compile because unlike sets, string arrays won't be expanded:
c.nim(2, 17) Error: type mismatch: got (Array constructor[0..1, string]) but expected 'string'
The not very pretty way to fix it is to write the proc like this:
proc test(ext: string) =
echo "Testing for ", ext
when md_extension.len != 2: {.fatal: "Missing case checks".}
case ext
of ".txt", md_extension[0], md_extension[1]:
echo "Found!"
else:
echo "Not found!"
Note the when check. This is to prevent the md_extension from being upgraded to more or less values in a different global module and the case not checking all the possible values. It works but requires the disciplined when and manually expanding the constant. In this particular example, without the when check, one could insert an extension at the beginning of md_extension and suddenly the check for .markdown would fail.
How could this be avoided? Maybe instead of such manual trickery define a macro which expands the array to the string literals for the case?