未初始化的数组在Julia中

8

假设我有一个 Julia 中的复合类型数组。我知道不能直接给数组赋值,因为它的元素是未定义的。例如下面的代码:

type struct
  u::Int64
  v::Int64
end

X = Array(struct, 100)
X[10].u = 3

会产生这个错误:

ERROR: access to undefined reference
 in getindex at array.jl:277
 in include at boot.jl:238
 in include_from_node1 at loading.jl:114

什么是处理这个问题的标准方法?目前,我只是做了类似这样的事情:
samples = Array(Sample1d, num_samples)
fill!(samples, Sample1d(0, 0, 0))
samples[i] = ...

有没有更简洁或者更优雅的方法来完成这个任务?
2个回答

7
你可以使用 fill 同时创建和填充一个数组:
type struct
  u::Int
  v::Int
end

struct() = struct(0, 0)
X = fill(struct(), 100)
X[10].u = 3

2

在数组中,您可以为未初始化的位置分配值。但是您无法从未初始化的位置提取值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接