what does the Keyword "where" mean in julia?

Viewed 1331
struct A{T<:myType}
    arg::T
    arg1
    function A{T}(arg,arg1) where {T}
        
        return new{T}(arg,arg1)
    end
end

my question is, why should I add where {T} beside the inner constructor. Without it I get :T is not defined

2 Answers

You can search for where in the REPL's help mode (accessed by pressing ?)

help?> where
search: where @where with_logger

  where

  The where keyword creates a type that is an iterated union of other types, over 
  all values of some variable. For example Vector{T} where T<:Real includes all 
  Vectors where the element type is some kind of Real number.

  The variable bound defaults to Any if it is omitted:

  Vector{T} where T    # short for `where T<:Any`

  Variables can also have lower bounds:

  Vector{T} where T>:Int
  Vector{T} where Int<:T<:Real

  There is also a concise syntax for nested where expressions. For example, this:

  Pair{T, S} where S<:Array{T} where T<:Number

  can be shortened to:

  Pair{T, S} where {T<:Number, S<:Array{T}}

  This form is often found on method signatures.

  Note that in this form, the variables are listed outermost-first. This matches 
  the order in which variables are substituted when a type is "applied" to 
  parameter values using the syntax T{p1, p2, ...}.

The reason you need to add the where {T} at the end of your function signature is that A is a parametric type with parameter T. If you leave only the A{T}, the function assumes you creating an instance of type A with parameter T, but T has not yet been defined. By adding the where {T}, you let the constructor know that T will be passed to the function as a parameter when it is called, not when it is defined.

To complement the @JackShannon answer, for functions there is also a difference in where the where is placed:

foo(x::T) where {T<:Number}  = x + one(T) # ok, I can use T within the function body
foo2(x::T where {T<:Number}) = x + one(T) # run time error T not defined
foo3(x::T where {T<:Number}) = x + 1      # ok, I am not using T inside the function body
Related