Hi I am a very beginner of the julia, when taking the online class, I found some examples they use “, vars" in the code. I am wondering what’s the meaning of ",” and why use it? Thanks
I think an example would be helpful.
Thank you for your reply. Here is one example:
function findclosest(data, point)
_, index = findmin(abs.(data .- point))
return data[index]
end
data = rand(5000)
findclosest(data, 0.5)
The _
is not actually in front of a variable in this case, it is a symbol used to destructure the tuple without storing its first element in a named variable. The function findmin
returns a tuple composed of a value and an index, but here we don’t care about the value so this is our way of telling Julia to not do anything with it.
In other settings, putting _
in front of a variable or function may also indicate that it is reserved for internal use in a package, and not part of the public API (in other words, steer clear of it)
I see, now it makes clear to me. BTW, is it a general rule that if we used “_,” then it means we are trying to ignore the first output of the function? Thanks
Yes. A bare underscore (or a number of underscores) is a valid variable name only on the left hand side of an assignment, so it’s a clear signal that you do not intend to use that variable - you can’t. Of course you could just as well use an actual variable name and just not use it, at no extra cost, but then you lose the signal.
Another common place you will see this is for _ = 1:50
which means “repeat loop 50 times, I don’t need a counter”.
Thank you for your clarification.
I’m curious: it is just ahestetics, or the compiler may take some advantage of that information, relative to using a random variable name? Is the underscore special in some sense for the compiler?
It is special cased in the parser (in lowering):
In [1]: 1 + _
ERROR: syntax: all-underscore identifier used as rvalue
But there aren’t really any optimizations that can be made from this.
In a closed scope I would imagine there’s no difference after compilation, the compiler will know it doesn’t need to store the variable, whether it has a name or no. In global scope maybe there is a performance difference. I don’t know.
This discussion is relevant: Dummy variable _ · Issue #9343 · JuliaLang/julia (github.com)