Hi,
I was wondering if its considered a feature or something that will be implemented in the future.
But right now, accessing an uninitialized variable not even compiles fine, but set a default value. I can imagine subtle bug to come out of this.
e.g.
import strutils
type
Person = object
name: string
age: Natural
var theValue: int
var theValue2 = 5
var thePerson: Person
# here I would expect uninitialized error!
echo theValue
echo theValue + theValue2
echo thePerson.name & "Hey"
echo thePerson.name.capitalizeAscii()
Easily done:
import strutils
type
Person {.requiresInit.} = object
name: string
age: Natural
var theValue: int
var theValue2 = 5
var thePerson: Person
# here I would expect uninitialized error!
echo theValue
echo theValue + theValue2
echo thePerson.name & "Hey"
echo thePerson.name.capitalizeAscii()
(And yeah, changing is this part of the unwritten v2 plan...)
Isn't this common behavior? Popular languages like C/C++, Java, Go... all compile fine without initializing fields of struct/class. Though you may get some warnings in some IDE.
All you need to do is to make the fields private and provide constructors.
Sometimes, I am wondering why people have so high expectation to Nim...
@Yardanico I know it compiles, but having possible uninitialized variable is a nest of hard to debug. My example is trivial (based on the webpage code). But on real use case with complex branching, that could be hard to find. Especially when it's initialized with a default value so you don't even have runtime error. Think VB and JS kinda weird behaviour.
@Araq I'm glad it's in the unwritten v2 plan ;-)
@jackhftang As for other languages. C#, TypeScript, Rust, Crystal will failed to compile in that scenario. One of many reasons I'm migrating all my JS to TS. I don't know if it's high exception or not. I do like Nim, I also know from experience that kind a 'flexibility' will cause pain at some point. So I'm curious to know if it's a design decision or something to fix later.
I have high expectations of Nim. why use it otherwise?
and when it does something you dont like, more often than not There's a Pragma For That(tm).