Initializing struct members after struct has been constructed

I’m trying to add members to my struct, but get:
BoundsError: attempt to access 0-element Array{Node,1} at index [1]

mutable struct Node
    i::Int
    j::Int
    floor::Bool
    neighbors::Array{Node}
    color::Union{String,Nothing}
    distance::Union{Int,Nothing}
    predecessor::Union{Node,Nothing}
end
Node(i, j, floor=true) = Node(i, j, floor, [], nothing, nothing, nothing)

A matrix called nodearray is full of initialized nodes, which currently has member neighbors initialized to ‘nothing’

nodearray[i,j].neighbors[n] = Node(i-1,j)

I am not able to add nodes as neighbors. Why?

Well, the problem is pretty much exactly as the error message says.
You have an 0-element Array{Node,1} (which comes from here: Node(..., --> [], ...)) and you want to put something at index [1], but that index doesn’t exist.

But you can still add something to the array: push!(nodearray[i,j].neighbors[n], Node(i-1,j)). The other option would be to initialize with an array which has enough space for your needs: Node(..., Vector{Node}(undef, 10), ...).

1 Like

push!() could be useful, I resolved it by initializing a fixed array size for neighbors in the construction. Thanks!

You’re welcome!