Julia 创建具有参数化返回类型的函数

Julia 创建具有参数化返回类型的函数,julia,Julia,我有一种情况,我想设置一个带有参数化返回类型的函数——下面是一个简化的示例。现在看来这是不可能的——用什么样的逻辑成语来代替呢?我并不清楚如何实现合理的代码重用 struct Output{T <: Number} other_details::String # lots of stuff here numeric_output::T end function get_output{T <: Number}(input)::Output{T} transfo

我有一种情况,我想设置一个带有参数化返回类型的函数——下面是一个简化的示例。现在看来这是不可能的——用什么样的逻辑成语来代替呢?我并不清楚如何实现合理的代码重用

struct Output{T <: Number}
    other_details::String # lots of stuff here
    numeric_output::T
end

function get_output{T <: Number}(input)::Output{T}
    transformed_input = input
    # Do stuff to transformed_input
    Output{T}(
        "lots of data",
        transformed_input
    )
end

input = 1::Int64
get_output{Float64}(input)

struct Output{T正如您可能已经注意到的,参数化定义的函数,例如
foo{T}(x)
之类的函数,只有在它们是类型(已经定义)的构造函数时才能定义。您可以改为将所需的输出类型作为函数参数,如下所示:

struct Output{T <: Number}
    other_details::String
    numeric_output::T
end

function get_output(::Type{T}, input) where {T <: Number}
    Output("lots of data", T(input))
end
请注意,文本
1
已经是一个整数。无需编写
1::Int64

还要注意在函数签名中使用a。这仅用于限制分派。您可以这样编写
get\u output
,这样就可以了:

get_output(T, input) = Output("lots of data", T(input))
顺便说一句,我强烈建议不要这样做,但可能会作弊,因为Julia编译器不强制构造函数实际返回它们应该构造的类型的实例:

struct Output{T <: Number}
    other_details::String
    numeric_output::T
end

struct get_output{T} end

function get_output{T}(input) where {T <: Number}
    Output("lots of data", T(input))
end

谢谢-这很好用。使用类型为一流公民的语言很有趣-这似乎是一个非常酷的特性。
struct Output{T <: Number}
    other_details::String
    numeric_output::T
end

struct get_output{T} end

function get_output{T}(input) where {T <: Number}
    Output("lots of data", T(input))
end
julia> get_output{Float64}(1)
Output{Float64}("lots of data", 1.0)