Yash Bhargava
Yash Bhargava

Reputation: 45

Parameters of Mutable struct same type as the struct

I am trying to create a mutable struct Neuron with a parameter inputs which is of type vector of Neuron. Is this possible in Julia. Following is what I am doing.

mutable struct Neuron
inputs::Vector{Neuron}
weights::Vector{Float64}
func::Function
output::Float64
#= parameters::Vector{Float64} =#
end

I am using julia 1.0. The error: ERROR: LoadError: invalid redefinition of constant Neuron

Upvotes: 0

Views: 417

Answers (1)

carstenbauer
carstenbauer

Reputation: 10157

Self-referential types are possible in Julia, as demonstrated in the Julia doc here: https://docs.julialang.org/en/v1.0.0/manual/constructors/#Incomplete-Initialization-1

The idea is that you use inner constructors and the new() constructor to create an incompletely initialized Neuron first and then use it to create other Neurons.

mutable struct Neuron
  inputs::Vector{Neuron}
  # forgetting about the other fields for a second
  Neuron() = new()
  # or alternatively Neuron() = begin (x=new(); x.inputs = [x]; x) end
end

Upvotes: 1

Related Questions