Typo in constructor, why does Julia not complain?

I made a type in my constructor (Tset instead of Test) and noticed that Julia does not complain if there is another function in the struct definition that has a different name than the struct itself. What happens to this line when I run my code and why is there no error?

struct Test
    a::Array{Float64, 3}
    Test(i) = new(rand(i, i, i))
    Tset(i, c) = new(rand(c*i, c*i, c*i))

test = Test(2)
# test = Test(2, 3)
1 Like

I assume that it ends up as dead code. Notice that you can do things like

julia> struct Foo
           Foo(x) = new(bar(x), bar(x + 1))
           bar(x) = x^2

julia> Foo(3)
Foo(9, 16)

so it can’t be an error to define other functions than the constructor itself.


OK thanks. I was unaware that such constructions were possible. Is this considered good style in Julia?



It doesn’t seem entirely unreasonable if you need a couple different inner constructors and they can share some code. But I’ve never seen it used and I only rarely use inner constructors at all myself.