-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
if nil guard doesn't work for instance variable #477
Comments
A temporary workaround is to use a local variable. |
asterite explained this here #398 (the first reply) |
I thought it was mentioned somewhere but here's why it doesn't: An instance variable is shared data, in a multi-threaded context it's possible that the condition is checked and matches, then control is given to another thread who sets the variable to nil and then control is given back to the thread that checked the variable and that is assuming now that it's not nil while it is. Also given that we do have parallelism these days, that scenario becomes even more likely.
|
Thanks again for the quick reply. I take it that this is the explanation (copied from asterite):
It would be cool to mention in the docs that the "if var" guard only works for local variables. Or to allow instance variables too, as this seems fairly easy for "if var". |
@jhass Bingo! @stefanwille It's explained in the docs: http://crystal-lang.org/docs/syntax_and_semantics/if_var.html (scroll to the bottom). It says "The above logic doesn’t work with instance variables, class variables or global variables" and explains why. |
@asterite Alright, found it, thanks! |
That being said, assigning to a local variable is a bit boring, and unexpected by newcomers, especially when there are no other methods setting I'm not sure, but, does Crystal complains when accessing |
Pretty sure it does. |
Yes it does, because getter is merely a |
@ysbaddaden maybe you were thinking about this https://github.com/manastech/crystal/blob/master/src/object.cr#L213 ? |
According to the docs (http://crystal-lang.org/docs/syntax_and_semantics/if_var.html) the compiler will assume that a variable 'var' can not be nil after a 'if var':
This works for local variables, but fails for instance variables:
For this example, I get a compile time error:
I would expect this to work the same as for local variables.
The text was updated successfully, but these errors were encountered: