# Using mutable struct constructor

**URL:** <https://discourse.julialang.org/t/using-mutable-struct-constructor/78179>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 20, 2022, 9:47pm UTC](https://discourse.julialang.org/t/using-mutable-struct-constructor/78179 "2022-03-20T21:47:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tgautam03](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tgautam03/32/20545_2.png) [@tgautam03](https://discourse.julialang.org/u/tgautam03)\
**Post date:** [March 20, 2022, 9:47pm UTC](https://discourse.julialang.org/t/using-mutable-struct-constructor/78179/1 "2022-03-20T21:47:37Z")

</div>

Hi

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

```julia
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.

```julia
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.

---

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [March 21, 2022, 1:48am UTC](https://discourse.julialang.org/t/using-mutable-struct-constructor/78179/2 "2022-03-21T01:48:26Z")

</div>

Is there a reason you can’t [mutate an instance with no defined fields?](https://docs.julialang.org/en/v1/manual/constructors/#man-inner-constructor-methods) Like so:

```julia
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](https://github.com/JuliaLang/julia/issues/36789) 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.

---

<div class="post-metadata">

**Author:** ![gdalle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gdalle/32/27854_2.png) [@gdalle](https://discourse.julialang.org/u/gdalle)\
**Post date:** [March 21, 2022, 5:41am UTC](https://discourse.julialang.org/t/using-mutable-struct-constructor/78179/3 "2022-03-21T05:41:34Z")

</div>

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

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

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

```
