I'm dealing with a type definition and some code in Nim, and everything was working smoothly before the transition to Nim 2.0. Here's the setup:
type
MenuItem = ref object
text: string
Menu = ref object
items: seq[MenuItem]
proc `=destroy`(self: var type(MenuItem()[])) =
echo "=destroy MenuItem"
proc `=destroy`(self: var type(Menu()[])) =
echo "=destroy Menu"
self.items.setLen(0)
when isMainModule:
var menu = Menu()
menu.items.add MenuItem(text: "item")
In Nim 2.0, I had to make changes to the destructors:
proc `=destroy`(self: type(MenuItem()[])) =
echo "=destroy MenuItem"
proc `=destroy`(self: type(Menu()[])) =
echo "=destroy Menu"
# self.items.setLen(0) <- error: type mismatch (not a var)
However, I noticed that the destructor for MenuItem is not being called. I found a somewhat hacky solution in (self.addr)[].items.setLen(0), but I'm wondering if there's a more elegant way to handle this situation without resorting to a workaround. Any suggestions would be greatly appreciated!
I believe this is the more "correct" way to deal with it:
type
MenuItemObj = object
text: string
MenuItem = ref MenuItemObj
MenuObj = object
items: seq[MenuItem]
Menu = ref MenuObj
proc `=destroy`(self: MenuItemObj) =
echo "=destroy MenuItem"
proc `=destroy`(self: MenuObj) =
echo "=destroy Menu"
`=destroy`(self.items)
when isMainModule:
var menu = Menu()
menu.items.add MenuItem(text: "item")
That being said neither of those types need a custom destructor in this sample, but I assume you have some C-interfacing logic in your actual codebase.