julia 中的关键字 "where" 是什么意思?

what does the Keyword "where" mean in julia?

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

我的问题是,为什么要在内部构造函数旁边添加 where {T}。没有它我得到:T is not defined

您可以在 REPL 的帮助模式中搜索 where(按 ? 访问)

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, ...}.

您需要在函数签名末尾添加 where {T} 的原因是 A 是带有参数 Tparametric type。如果您只保留 A{T},该函数假定您创建了一个类型为 A 且参数为 T 的实例,但尚未定义 T。通过添加 where {T},您让构造函数知道 T 将在函数被调用时作为参数传递给函数,而不是在函数定义时。

为了补充@JackShannon 的回答,对于函数,where 的放置位置也有所不同:

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