tuse_ownedref_after_move.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. discard """
  2. cmd: '''nim c --newruntime $file'''
  3. errormsg: "'=copy' is not available for type <owned Button>; requires a copy because it's not the last read of ':envAlt.b0'; routine: main"
  4. line: 48
  5. """
  6. import system / ansi_c
  7. type
  8. Widget* = ref object of RootObj
  9. drawImpl: owned(proc (self: Widget))
  10. Button* = ref object of Widget
  11. caption: string
  12. onclick: owned(proc())
  13. Window* = ref object of Widget
  14. elements: seq[owned Widget]
  15. proc newButton(caption: string; onclick: owned(proc())): owned Button =
  16. proc draw(self: Widget) =
  17. let b = Button(self)
  18. echo b.caption
  19. result = Button(drawImpl: draw, caption: caption, onclick: onclick)
  20. proc newWindow(): owned Window =
  21. proc draw(self: Widget) =
  22. let w = Window(self)
  23. for e in w.elements:
  24. if not e.drawImpl.isNil: e.drawImpl(e)
  25. result = Window(drawImpl: draw, elements: @[])
  26. proc draw(w: Widget) =
  27. if not w.drawImpl.isNil: w.drawImpl(w)
  28. proc add*(w: Window; elem: owned Widget) =
  29. w.elements.add elem
  30. proc main =
  31. var w = newWindow()
  32. var b = newButton("button", nil)
  33. b.onclick = proc () =
  34. b.caption = "clicked!"
  35. w.add b
  36. w.draw()
  37. # simulate button click:
  38. b.onclick()
  39. w.draw()
  40. main()