Julia:“<:"是什么意思?符号是什么意思? [英] Julia: what does the "<:" symbol mean?

查看:48
本文介绍了Julia:“<:"是什么意思?符号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在函数签名中是什么意思,例如:

What does this mean in function signatures, for example:

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

推荐答案

严格来说,应该区分谓词 Base.:(<:),如@Saqib 的回答中所述,和<: 用于描述约束的语法用法.

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)

这种情况的一种特殊情况是当您约束结构的类型参数时 (struct Foo{T<:Real} ... end) —— 约束生成的方法构造函数,并允许类型构造函数仅应用于受约束的子类型.

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

虽然这两种情况都符合子类型谓词的含义,但你不能用其他任意表达式替换它们(例如,你不能写 ... where {isreal(T)}f 中的代码>).

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).

这篇关于Julia:“&lt;:"是什么意思?符号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆