Hi, i tried create an object that has object variants using alloc(size: Natural) but when assigning the variant kind it throws an exception, is there a way for assign it without creating an auxiliar object or without using -d:nimOldCaseObjects?, here is a example:
type
Kinds = enum
kA, kB, kC
ExampleBlock = object
case kind: Kinds
of kA: a: int
of kB: b: string
of kC: c: uint16
otherFields: array[16, int]
when isMainModule:
echo "Sizeof block, ", sizeof(ExampleBlock) # Is a union after all
let kindcrash = cast[ptr ExampleBlock](
alloc0(sizeof(ExampleBlock))
)
kindcrash.kind = kB # Crash Here
kindcrash.b = "String Test"
echo kindcrash.b
I don't see a crash here, just a normal error message:
: unhandled exception: assignment to discriminant changes object branch; compile with -d:nimOldCaseObjects for a transition period [FieldError]
The way case objects are handled has changed. Now they can only be created with a specific case, they can't be set at runtime. You are trying to set it at run time.
I can't think of other ways around this rule other then "creating and copying the object" or "using -d:nimOldCaseObjects"... There probably is but it will be just as ugly.
Maybe you don't need case objects? Maybe you don't need alloc0 them? Are you using pointers because of threads?
Auxiliary copy object does not fill too bad though:
type
Kinds = enum
kA, kB, kC
ExampleBlock = object
case kind: Kinds
of kA: a: int
of kB: b: string
of kC: c: uint16
otherFields: array[16, int]
when isMainModule:
echo "Sizeof block, ", sizeof(ExampleBlock) # Is a union after all
let kindcrash = cast[ptr ExampleBlock](
alloc0(sizeof(ExampleBlock))
)
var copyObj = ExampleBlock(kind:kb)
copyObj.b = "String Test"
kindcrash[] = copyObj
echo kindcrash.kind
echo kindcrash.b