What is the meaning of <: in julia?

Viewed 139

Can anyone help me with this code:

struct GenericPoint{T<:Real}
x::T
y::T
end

What is meaning of <: in {T<:Real} in Julialang?

1 Answers

Let me begin by saying that the punctuation page of the manual is a handy way to search for such operators, which are otherwise very difficult to look for using a search engine. In the specific case of <:, we find this page, with the relevant documentation for essential operators.

There are (at least) 3 contexts where A <: B might be used, and in all of them this expresses the idea that A is a subtype of B.

  1. as a predicate, A <: B returns true if and only if all values of type A are also of type B:
julia> Int <: Number
true

julia> Int <: AbstractString
false
  1. in a type definition, this declares that the newly defined type is a subtype of an existing (abstract) type:
# `Foo` is declared to be a subtype of `Number`
struct Foo <: Number
end
  1. as a type-parameter constraint (like in your example), T <: Real expresses the idea that type parameter T can be any subtype of 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

Note that the use for type-parameter constraints is not restricted to the definition of parametric types, but also applies to function/method definitions:

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})
Related