You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Okay, I'm not even sure that using var in conjunction with return types does make any sense at all. The thing is, the compiler allows it in some circumstances, but then we'll get segfaults at runtime.
Short version:
procmakeSeqVar(size: Natural): varseq[int] =newSeq(result, size)
# This will result in a segfaultdiscardmakeSeqVar(1000)
# var.nim(4) var# var.nim(2) makeSeqVar# system.nim(1758) unsureAsgnRef# SIGSEGV: Illegal storage access. (Attempt to read from nil?)
However, the compiler seems to be doing a good job of preventing this from happening for simple types:
procstuff(): varstring=result="mayhem"# var.nim(2, 12) Error: expression has no addressdiscardstuff()
How I ended up with this construct in the first place:
procdoStuff(s: varseq[int]) =for i in0..s.high:
s[i] =42procmakeSeq(size: Natural): seq[int] =newSeq(result, size)
# Case #1 - this is all good so farvar s1 =makeSeq(1000)
doStuff(s1)
# Case #2 - generates compiler error, which is CORRECT# doStuff(makeSeq(1000))# var.nim(11, 8) Error: type mismatch: got (seq[int])# but expected one of:# proc doStuff(s: var seq[int])# for a 'var' type a variable needs to be passed, but 'makeSeq(1000)' is immutable# Case #3 - let's try changing the return type to var seq[int]procmakeSeqVar(size: Natural): varseq[int] =newSeq(result, size)
# This will compile fine now...doStuff(makeSeqVar(1000))
# ...but not so fast, it will FAIL spectacularly at runtime:## var.nim(25) var# var.nim(23) makeSeqVar# system.nim(1758) unsureAsgnRef# SIGSEGV: Illegal storage access. (Attempt to read from nil?)# And it turns out that just doing this triggers the failure:discardmakeSeqVar(1000)
The text was updated successfully, but these errors were encountered:
Okay, I'm not even sure that using
var
in conjunction with return types does make any sense at all. The thing is, the compiler allows it in some circumstances, but then we'll get segfaults at runtime.Short version:
However, the compiler seems to be doing a good job of preventing this from happening for simple types:
How I ended up with this construct in the first place:
The text was updated successfully, but these errors were encountered: