import asyncdispatch
type testType = object
testField: bool
proc testProc(thing: var testType) {.async.} =
if not thing.testField:
thing.testField = true
var x: testType
waitFor testProc(x)
https://play.nim-lang.org/#ix=3IGJ
results in:
Error: 'thing' is of type <var testType> which cannot be captured as it would violate memory safety, declared here: /usercode/in.nim(8, 15); using '-d:nimNoLentIterators' helps in some cases
Quick question. Making testType a ref object fixed the issue but does it still need to be a var? The code still works when I use let which is slightly confusing to me.
e.g.:
import asyncdispatch
type testType = ref object
testField: bool
proc testProc(thing: testType) {.async.} =
if thing.testField:
thing.testField = false
proc newThing(): testType =
new result
result.testField = true
let x = newThing()
waitFor testProc(x)
echo x.testField
I admittedly have very little experience with ref types.
To elaborate an immutable reference just means the reference cannot be reassigned but the pointed at object and all of its fields can be mutated so the following happens:
var a = 100
a = 300 # Can reassign `a` (var int)
assert a == 300
let b = 100
#b = 300 # Cannot reassign `b` (let int)
let c = new int
c[] = 300 # We're assigning what `c` points to which is valid
assert c[] == 300
#c = new int # Cannot reassign `c` (let ref T)
var d = new int
d[] = 400
assert d[] == 400
d = new int # Can reassign `d` (var ref T)