【问题标题】:Julia handling void return typeJulia 处理 void 返回类型
【发布时间】:2016-10-06 00:24:45
【问题描述】:

当函数返回 Void 类型时,最好的处理方法是什么? http://docs.julialang.org/en/release-0.5/manual/faq/#how-does-null-or-nothingness-work-in-julia 中的建议不起作用。

MWE(必须从 REPL 运行,因此 Base.source_dir() 返回 Void):

julia> isempty(Base.source_dir())
ERROR: MethodError: no method matching start(::Void)
Closest candidates are:
  start(::SimpleVector) at essentials.jl:170
  start(::Base.MethodList) at reflection.jl:258
  start(::IntSet) at intset.jl:184
  ...
 in isempty(::Void) at ./iterator.jl:3
 in isempty(::Void) at /Applications/Julia-0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?

julia> isdefined(Base.source_dir())
ERROR: TypeError: isdefined: expected Symbol, got Void

julia> typeof(Base.source_dir()) == Void
true

这是在 Julia 0.5 上。后一个选项有效,但有点难看。

【问题讨论】:

    标签: julia


    【解决方案1】:

    Void 是一个单例——一种只有一个实例的类型。 那一个实例是Void(),也称为nothing。 请注意nothing === Void()

    您可以像对待任何其他值一样对待它。

    它是由一堆函数返回的,比如println

    您可以检查是否返回了 nothing —— 即 Void 类型的实例。

    julia> println()===nothing
    true
    

    为了类型稳定性, 一个方法在某些时候不应该返回nothing,在某些时候不应该返回一些东西。 在这种情况下,它应该返回一个Nullable, 一般。

    【讨论】:

    • === 通常被推荐,因为它可以以奇怪的方式扩展==
    猜你喜欢
    • 2012-08-02
    • 2015-06-29
    • 2015-03-24
    • 1970-01-01
    • 2017-02-28
    • 2016-08-16
    • 2011-04-08
    • 2013-02-24
    • 2013-06-20
    相关资源
    最近更新 更多