One of the things that I currently find very concerning about object variants 
is how they can introduce runtime errors when the discriminator is assigned to 
in an incorrect manner. As it turns out, there [seems to be a compiler 
bug](https://github.com/nim-lang/Nim/issues/6918) that causes not only 
exceptions, but undefined behavior when the discriminator is changed. Also see 
[this RFC](https://github.com/nim-lang/Nim/issues/6921).

I always prefer catching these sorts of problems at compile time, and it 
occurred to me that making the discriminator private could offer a solution in 
some cases.
    
    
    type
      Variants* = enum
        vaCow, vaPig, vaHorse
      
      MyObj = object
        case kind: Variants
        of vaCow:
          age*: float
        of vaPig:
          hunger*: Natural
        of vaHorse:
          name*: string
    
    proc newMyObj*(age: float): MyObj =
      MyObj(kind: vaCow, age: age)
    
    proc kind*(o: MyObj): Variants =
      o.kind
    

So, do you think that this is an idomatic/Nim-esque solution? I feel that it 
solves the problem of safety when the "kind" will be determined by a 
constructor proc and remain constant, as in the example.

I am tempted to use this pattern often, as I highly value memory safety. Will I 
encounter pitfalls/confusion with this, or is it an acceptable workaround?

Reply via email to