<: 在朱莉娅中是什么意思?

Rah*_*war 3 julia

任何人都可以帮助我使用此代码:

struct GenericPoint{T<:Real}
x::T
y::T
end
Run Code Online (Sandbox Code Playgroud)

<:in{T<:Real}在Julialang中是什么意思?

ffe*_*tte 8

首先让我说,手册的标点页面是搜索此类操作符的便捷方式,否则使用搜索引擎很难找到这些操作符。在 的特定情况下<:,我们可以找到此页面,其中包含基本操作员的相关文档。

有(至少)3 个上下文A <: B可以使用,并且在所有上下文中这都表达了A作为B.

  1. 作谓语,A <: B返回true当且仅当类型的所有值A的类型也B
julia> Int <: Number
true

julia> Int <: AbstractString
false
Run Code Online (Sandbox Code Playgroud)
  1. 在类型定义中,这声明新定义的类型是现有(抽象)类型的子类型:
# `Foo` is declared to be a subtype of `Number`
struct Foo <: Number
end
Run Code Online (Sandbox Code Playgroud)
  1. 作为类型参数约束(如您的示例中),T <: Real表达了类型参数T可以是 的任何子类型的想法Real
julia> struct GenericPoint{T<:Real}
           x::T
           y::T
       end

# Works because 1 and 2 are of type Int, and Int <: Real
julia> GenericPoint(1, 2)
GenericPoint{Int64}(1, 2)

# Does not work because "a" and "b" are of type String,
# which is not a subtype of Real
julia> GenericPoint("a", "b")
ERROR: MethodError: no method matching GenericPoint(::String, ::String)
Stacktrace:
 [1] top-level scope at REPL[5]:1
Run Code Online (Sandbox Code Playgroud)

请注意,类型参数约束的使用不仅限于参数类型的定义,还适用于函数/方法定义:

julia> foo(x::Vector{T}) where {T<:Number} = "OK"
foo (generic function with 1 method)

# OK because:
# - [1,2,3] is of type Vector{Int}, and
# - Int <: Number
julia> foo([1, 2, 3])
"OK"

# Incorrect because:
# - ["a", "b", "c"] is of type Vector{String}, but
# - String is not a subtype of Number
julia> foo(["a", "b", "c"])
ERROR: MethodError: no method matching foo(::Array{String,1})
Run Code Online (Sandbox Code Playgroud)