Using mutable struct constructor

Hi

I’ve defined a mutable struct with constructor that initialises the first field as follows

mutable struct Dummy
	val1::Array
	val2::Array

	function Dummy(val1::Array)
		new(val)
	end
end

Is there a way I can define a constructor such that 2nd value is initialised and 1st value is undef? I tried something like the code below but it’s giving me an error.

mutable struct Dummy
	val1::Array
	val2::Array

	function Dummy(val2::Array)
		new(undef, val)
	end
end

P.S. My original code is much complicated with many more fields and it’ll not be intuitive to put val1 at the end of fields.

Is there a reason you can’t mutate an instance with no defined fields? Like so:

mutable struct Dummy
	val1::Array
	val2::Array

	function Dummy(val::Array)
		out = new()
		out.val2 = val
		out
	end
end

There’s also a discussion here about somehow allowing new to accept keyword arguments to choose uninitialized fields more concisely. Goes into interesting topics like immutable instances with uninitialized fields and replacing uninitialized fields entirely.

2 Likes

Hi!
I like the answer given above, but just in case, you can also use union types and Base.@kwdef, like so:

mutable struct Dummy
	val1::Union{Nothing,Array}
	val2::Array

	function Dummy(val2::Array)
		new(nothing, val2)
	end
end