【问题标题】:function return type from assignement赋值的函数返回类型
【发布时间】:2017-10-10 17:58:16
【问题描述】:

这里我期望的是 Int 类型,但得到了 Float:

julia> function test()
         i::Int = 3.0
       end
test (generic function with 1 method)

julia> typeof(test())
Float64

在这种情况下,返回类型是 Int:

julia> function test()
         i::Int = 3.0
         i
       end
test (generic function with 1 method)

julia> typeof(test())
Int64

这是正确的行为还是错误?

【问题讨论】:

  • 一个陷阱,但不是一个错误。一个很好的例子,说明为什么显式返回语句通常是个好主意!

标签: julia


【解决方案1】:

这是杰夫的一句话:

= returns the right-hand side every time. No exceptions.

所以在第一个例子中,相当于直接返回=返回的内容,即3.0:

julia> @code_lowered test()
CodeInfo(:(begin 
        nothing
        SSAValue(0) = 3.0
        i = (Core.typeassert)((Base.convert)(Main.Int, SSAValue(0)), Main.Int)
        return SSAValue(0)
    end))

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多