使用f(x::Real)
和f{T <: Real}(x::T)
来定义函数有什么区别吗?
@code_warntype
会对以下两个函数给出相同的输出:
function f(x::Real)
x^2
end
function g{T <: Real}(x::T)
x^2
end
function pow{T <: Real}(base::T, exponent::T)
base^power
end
T
是必要的,以强制确保 base
和 exponent
具有相同的类型,限制是该类型必须是 Real
的子类型。function pow(base:: Real, exponent:: Real)
base^power
end
现在这个函数要求base
和exponent
都是Real
的子类型,但是没有类型关系来强制要求两者都是Real
的相同子类型。
建议使用 f(x::Real)
。额外的不必要类型参数会使编译器难以处理并减慢动态分派速度,同时对其他人阅读也更加困难。
请参考 风格指南:
Don’t use unnecessary static parameters
A function signature:
foo{T<:Real}(x::T) = ...
should be written as:
foo(x::Real) = ...
instead, especially if T is not used in the function body. Even if T is used, it can be replaced with typeof(x) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.
Note also that container types, specifically may need type parameters in function calls. See the FAQ Avoid fields with abstract containers for more information.
foo{x::T, y::T}(x::T, y::T)
和foo(x::T, y::T) where {x::T, y::T}
怎么样?哪种风格更受欢迎?foo{x::T, y::T}(x::T, y::T)
在0.6版本中是否已被弃用? - amrodsfoo{T}(x::T, y::T)
吗?如果你使用的是0.6版本,请优先考虑foo(x::T, y::T) where {T}
。 - Fengyang Wang