关于julia:Inside type definition is reserved:Defining a array of structures inside another structure

Inside type definition is reserved: Defining an array of structures inside another structure

当我尝试在另一个结构中包含结构数组时,Julia 会引发错误。

1
ERROR: LoadError: syntax:"grid = Cell[]" inside type definition is reserved

这是我要运行的测试代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Cell
    color::Int64
    location::Int64
    Cell(color::Int64,location::Int64) = new(color,location)
    Cell()=new(0,0)
end

struct Grid
    dimensions::Int64
    timestep::Int64
    grid=Cell[]
    courseGrain=Cell[]
    Grid(dimensions::Int64,timestep::Int64,grid_cell::Cell,courseGrain_cell::Cell) =
    new(dimensions,timestep,push!(grid,grid_cell),push!(courseGrain,courseGrain_cell))
end

目前不允许在字段声明中定义默认字段值。见 https://github.com/JuliaLang/julia/issues/10146

为了实现你想要的,将你的 gridcourseGrain 定义为 Cell 类型的一维数组,即 Array{Cell, 1} 或等效的 Vector{Cell},并在构造函数中处理默认情况。

1
2
3
4
5
6
7
8
struct Grid
    dimensions::Int64
    timestep::Int64
    grid::Vector{Cell}
    courseGrain::Vector{Cell}
    Grid(dimensions::Int64,timestep::Int64,grid_cell::Cell,courseGrain_cell::Cell) =
    new(dimensions,timestep,[grid],[courseGrain_cell])
end

如果您希望您的构造函数之一创建一个空的 gridcourseGrain,您可以在对 new.

的调用中编写 Cell[]Vector{Cell}(undef, 0)