内部类型定义保留

Yau*_*ich 1 julia

在0.3中工作的代码:

type foo
    bar::Int = 0
end
Run Code Online (Sandbox Code Playgroud)

迁移到Julia 0.4之后,会产生类似

julia4 test.jl
ERROR: LoadError: syntax: "bar::Int=0" inside type definition is reserved
 in include at ./boot.jl:254
 in include_from_node1 at loading.jl:133
 in process_options at ./client.jl:306
 in _start at ./client.jl:406
Run Code Online (Sandbox Code Playgroud)

错误是什么意思?如何在0.4-中修复它?

NB

我了解这是一个开发版本。我也用Google搜索并查阅了手册http://julia.readthedocs.org/en/latest/manual/types/

Yau*_*ich 6

好的,我想到的是使用构造new()函数和一个带有默认(python / haskell式)参数值的函数(类型):

type Foo
    bar::Int

    function Foo(bar=0)
        new(bar)
    end
end


x = Foo()
Run Code Online (Sandbox Code Playgroud)

显然,较短的语法版本暂时不起作用:

编辑较短的版本也可以正常工作(thnx @ivarne)

type Foo
    bar::Int

    Foo(bar=0) = new(bar)
end
Run Code Online (Sandbox Code Playgroud)

重要的是,该解决方案在0.3和0.4均可工作,因此无需使用if VERSION .. else .. end

注意:如果您在foo类型中有多个变量,则只需在最后一行添加逗号即可说明其他变量!

  • 您不希望使用``function''关键字进行简短声明。 (2认同)