kilgoretrout
kilgoretrout

Reputation: 3657

Julia: what does the "<:" symbol mean?

What does this mean in function signatures, for example:

convert(::Type{T}, z::Complex) where {T<:Real}

Upvotes: 6

Views: 429

Answers (2)

phipsgabler
phipsgabler

Reputation: 20970

Strictly speaking, one should differentiate between the predicate Base.:(<:), as described in @Saqib's answer, and the syntactic usage of <: for describing constraints.

This syntactic usage can occur in type parameter declarations of methods, to constrain a type variable to be a subtype of some other type:

f(x::T) where {T<:Real} = zero(x)

A sort of special case of this is when you constrain the type parameter of a struct (struct Foo{T<:Real} ... end) -- that constrains the methods of the generated constructor, and allows the type constructor to be applied only to the constrained subtypes.

On the other hand, outside of type parameters, <: can be used to declare a new type as a subtype of some other (necessarily abstract) type:

struct Foo <: Real end

Although both cases are in line with the meaning of the subtyping predicate, you can't replace them with other arbitrary expressions (e.g., you can't write ... where {isreal(T)} in f).

Upvotes: 10

Saqib Shahzad
Saqib Shahzad

Reputation: 1002

<:(T1, T2)

Subtype operator: returns true if and only if all values of type T1 are also of type T2.

Examples:

Float64 <: AbstractFloat
=> true

Vector{Int} <: AbstractArray
=> true

Matrix{Float64} <: Matrix{AbstractFloat}
=> false

Upvotes: 7

Related Questions