Julia 内部类型定义是保留的
在0.3中工作的代码:Julia 内部类型定义是保留的,julia,Julia,在0.3中工作的代码: type foo bar::Int = 0 end 迁移到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 ./cl
type foo
bar::Int = 0
end
迁移到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
这个错误意味着什么?如何将其固定在0.4-
铌
我知道这是一个开发版本。我也在谷歌上搜索并查阅了手册好的,我想到的是使用名为
new()
的构造函数和带有默认(类似python/haskell)参数值的函数(类型):
struct Foo
bar::Int
function Foo(bar=0)
new(bar)
end
end
x = Foo()
较短的语法版本是(thnx@ivarne)
我认为你所谓的“默认字段值”从来没有像你预期的那样工作过,但在未来(0.6 ish)它可能会工作。请参见内部构造函数用于强制执行不变量,在这种情况下,您只需要定义方法
Foo()
,注意方法Foo(bar=0)
只创建Foo()
:
现在启动一个新会话并键入:
julia> struct Foo
bar::Int
end
julia> Foo(bar=0) = Foo(bar)
Foo
julia> methods(Foo)
# 3 methods for type constructor:
[1] Foo() in Main at REPL[3]:1
[2] Foo(bar::Int64) in Main at REPL[2]:2
[3] Foo(bar) in Main at REPL[3]:1
您不需要将
函数
关键字用作简短声明。这两个版本都可以使用。正如@irvane提到的,您忘记删除函数
关键字。
julia> type Foo
bar::Int
end
julia> methods(Foo)
# 2 methods for type constructor:
[1] Foo(bar::Int64) in Main at REPL[1]:2
[2] Foo(bar) in Main at REPL[1]:2
julia> Foo() = Foo(0)
Foo
julia> methods(Foo)
# 3 methods for type constructor:
[1] Foo() in Main at REPL[3]:1
[2] Foo(bar::Int64) in Main at REPL[1]:2
[3] Foo(bar) in Main at REPL[1]:2
julia> struct Foo
bar::Int
end
julia> Foo(bar=0) = Foo(bar)
Foo
julia> methods(Foo)
# 3 methods for type constructor:
[1] Foo() in Main at REPL[3]:1
[2] Foo(bar::Int64) in Main at REPL[2]:2
[3] Foo(bar) in Main at REPL[3]:1