I'd like an object variant where both variants have the kind and field1 fields, but only in case of kind == kind2, I want an additional field field2.
I can model this with
type
MyKind =
enum kind1, kind2
MyObject = object
case kind: MyKind
of kind1:
discard
of kind2:
field2: string
field1: string
but I'm wondering if it's somehow possible to specify the fields in the order kind, field1, field2.
I tried
type
MyKind =
enum kind1, kind2
MyObject = object
case kind: MyKind
of kind1:
field1: string
of kind2:
field1: string
field2: string
but then the compiler complains
Error: attempt to redefine: 'field1'
It's worse if you have something like this:
type
MyKind =
enum kind1, kind2, kind3
MyObject = object
case kind: MyKind
of kind1:
field2: string,
field3: string
of kind2:
field1: string
field3: string
of kind3:
field1: string
field2: string
As far as I can tell, there's no way to get this to compile, because every field name appears twice and is supposed to be used for two of the kinds.
I'm wondering if the compiler check should be relaxed here, maybe turned into a hint.
Of course you could work around the issue by renaming the fields for the different cases, but if the semantics of the field is the same for different cases it would in my opinion more natural to be able to use the same name.
What do you think?
I just found
https://github.com/nim-lang/RFCs/issues/19
which discussed the issue and has two suggestions for a possible syntax. (I had already used a generic web search, but now searched in the Nim tickets.)
One of the syntax suggestions would look like the posting above, the other like
MyObject = object
case kind: MyKind
of kind2, kind3:
field1: string
of kind1, kind3:
field2: string
of kind1, kind2:
field3: string