gpt4 book ai didi

types - f(x::Real) 和 f{T <: Real}(x::T) 的区别?

转载 作者:行者123 更新时间:2023-12-04 22:56:32 26 4
gpt4 key购买 nike

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

最佳答案

参数化类型T实际上并不用于表达类型之间的任何关系,因此使用它的理由很少,这只会增加不必要的复杂性。

这是一个示例,其中需要使用参数类型:

function pow{T <: Real}(base::T, exponent::T)
base^power
end

在这种情况下, T有必要强制执行这两个 baseexponent具有相同的类型,但限制该类型必须是 Real 的子类型.

相比之下,这是相同的函数,不使用参数类型:
function pow(base:: Real, exponent:: Real)
base^power
end

现在这个功能需要 baseexponentReal 的子类型,但没有类型关系强制两者属于 Real 的相同子类型.

关于types - f(x::Real) 和 f{T <: Real}(x::T) 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com