What if you could declare let and const like var?
let x: int
Without "Error: 'let' symbol requires an initialization"
let x: int
if true:
x = 1
else:
x = 0
# x can only be assigned to once
Another use:
let result: bool
# long complicated proc body
return result
You get an error if result is assigned to more than once. You also get an error if it is never given a value.
For the first you can write:
let x =
if true:
1
else:
0
For the second you can just write the value as the last statement without a result variable:
proc foo: bool =
var x = 10
if true:
inc x
else:
dec x
x > 10
just write the value as the last statement without a result variable:
Interesting, I missed that from the manual. Like Ruby :-)
It is considered good style? I asked myself if I should write "result = x > 10" or "return x > 10". I used the later -- but now I may indeed use the last expression without "return" as in Ruby. Personally I like that for short procs.
Maybe we may get the "a = 1 if expression" syntax from Ruby for Nim 2.0? I miss that sometimes.
[EDIT]
Indeed I am confused: Was the idea of the result variable to have a default value? So if the default is false or 0, and last expression in a proc is "true" or "1" -- so what is the return value of the proc? No idea currently , I have to consult the manual...
Stefan_Salewski:
The return value is the expression at the end of the proc, if there is one, otherwise result variable, that has a default value. In Ruby everything is an expression, no expression/statement differentiation, so it cannot have default values. In Nim you have to discard expressions, turning them to statements, except for the last expression in the proc.