我在其他人的代码中看到了以下内容,但我从未用自己的代码编写过,因为我不明白发生了什么.
I have seen the following in other people's code, but I've never written it in my own since I didn't understand what was happening.
举个例子:
函数 add(x::T, y::T) 其中 {T :<整数}
我猜测 T 被转换为整数,然后用于显式键入 x 和 y.但是为什么不直接做 x::Int64 呢?在哪里 {T :<Integer} 允许任何 Int 类型,例如 Int32 和 Int64?
I am guessing that T is being cast as an Integer and then used to explicitly type x and y. But why not just do x::Int64? Does where {T :< Integer} allow for any Int type like Int32 and Int64?
推荐答案稍微扩展一下 Oscar 的回答:
To expand a little on Oscar's answer:
使用 function add(x::T, y::T) where {T :<Integer} 允许您将 参数方法 添加到函数 add(x, y).您可以在 参数方法.
Using function add(x::T, y::T) where {T :< Integer} allows you to add a parametric method to the function add(x, y). You can read up on this in more detail in the Julia documentation under Parametric Methods.
这有两大优势:它允许您定义合理的通用方法(因为在许多情况下,整数的确切类型不会真正影响函数定义).同时它允许您将调用限制为相同类型的 x, y 对,这可以提高类型稳定性并导致更高效的编译代码.
This comes with two big advantages: It allows you to define reasonably general methods (since in many cases the exact type of integer would not really affect the function definition). Simultaneously it allows you to restrict the call to x, y pairs of the same type, which can improve type stability and lead to more efficient compiled code.
更多推荐
`where {t :< 是什么意思?Integer}` 在 Julia 函数声明的上下文中是什么意思?
发布评论