在Julia中,关键字"where"是什么意思?

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

我的问题是,在内部构造函数旁边为什么要添加 where {T}。如果没有它,我会得到:T未定义
2个回答

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

你需要在函数签名末尾添加 where {T} 是因为A是一个带有参数T参数化类型。如果只留下 A{T},则函数会认为你正在创建带有参数TA 类型的实例,但此时 T 尚未定义。通过添加 where {T},你让构造函数知道 T 将在调用函数时作为参数传递进来,而不是在定义时就确定。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接