Hi there, after looking at pieces of code around the internet, I have occasionally seen codes where functions are defined with function foo(x, v::T) where T
, or something like that. I don’t understand the point of this where T
at the end. If T
is a type, then if you aren’t restricting it with a line like where T<:Float64
or something like that, how does the where T
at the end contribute in any way?
Usually this is because you want to use T
in the function body.
Oh I see. So the function I wrote in the example would enable you to access the type T in the function. I just checked on a REPL to see that you indeed can NOT access the type T if you just write function foo(x, v::T)
. Thanks for your help!
Yes, the where
clause of a function signature declares “parametric” types. Without it, the compiler goes to look for the literal type T
and errors because it has not been defined.
Side note, this is used when you want access to T in the function body as @fredrikekre but it can also be used when you want two arguments of the same type, but you don’t care what types. Like:
same_type(::Any, ::Any) = false
same_type(::T, ::T) where T = true
Yet another reason you might see this, where T
may not even be used in the function body, is to force specialization in some cases where Julia otherwise would not.