朱莉娅中的关键字“where”是什么意思?

ahm*_*hm5 6 constructor struct where-clause julia

struct A{T<:myType}
    arg::T
    arg1
    function A{T}(arg,arg1) where {T}
        
        return new{T}(arg,arg1)
    end
end
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么我应该在内部构造函数旁边添加where {T} 。没有它我得到:T 未定义

小智 6

您可以在 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, ...}.
Run Code Online (Sandbox Code Playgroud)

where {T}您需要在函数签名末尾添加 的原因是它A是带有参数的参数类型T。如果仅保留,则该函数假定您使用参数A{T}创建类型的实例,但尚未定义。通过添加,您可以让构造函数知道 它将在调用函数时(而不是定义函数时)作为参数传递给函数。ATTwhere {T}T


Ant*_*llo 5

为了补充@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
Run Code Online (Sandbox Code Playgroud)