'for loop' and Nothing

Nothing (pun intended) “surprised” me a little bit…

   foo = nothing
   for x in foo
       println("should not see this")
   end

Instead of silently skipping the whole for x block, I got
ERROR: MethodError: no method matching iterate(::Nothing). Nothing ( xD ) I can’t work with, but I (hoped? expected?) ‘for’-loop’d treat Nothing as an empty/zero iterator.

P.S.: this isn’t a question, just a brief observation.

The error makes sense to me - nothing can be seen here as “no thing” to iterate over, which is not the same as an empty collection. Having it iterable would imo only lead to more confusing behavior like

for x in 1
   println(x) # prints 1!
end
1 Like

Oh, aye, that’d be weird indeed. I certainly can live with how it is right now anyway - was just tinkering with a thought of using e.g. Union{Nothing, Vector{...}} style at a few parts of code (but there’s simpler ways in existence than messing with that beehive, I know).

Yeah, that’s its intended use! You can use something to access e.g. a field with that type. Sometimes I wish it’d only unpack Some, but alas, that’s not the world we live in and changing that behavior is breaking.

1 Like

something… that’s handy. A bugger to try google tho.

Note also that you’re iterating the type Nothing here, while nothing is the corresponding singleton value. Although your error message fits iterating nothing, so maybe it was just a copy error.

1 Like

You can query docstrings from the REPL, like julia>?something which enters help mode and displays any docstrings associated with the given symbol.

1 Like

Yeah, typo in post, foo = Nothing oughta read foo = nothing.

because of this actually I was expecting that for x in nothing printed nothing.