Hide default constructor for a struct

Is there a way to hide a default constructor for a struct so that it is not callable?

Thanks.

You can certainly replace the default constructor by a custom one. But dropping it without any replacement isn’t particularly useful, is it? If there is no constructor at all, what do you need the struct for (you will never be able to create objects)?

julia> struct A
           x::Float64
           A() = new(1.23)
       end

julia> A() # custom constructor
A(1.23)

julia> A(3.141) # default constructor isn't defined
ERROR: MethodError: no method matching A(::Float64)
Closest candidates are:
  A() at REPL[1]:3
Stacktrace:
 [1] top-level scope
   @ REPL[3]:1

FWIW, you can also delete the constructor methods after defining the struct.

julia> struct A
           x::Float64
       end

julia> Base.delete_method.(methods(A));

julia> methods(A)
# 0 methods for type constructor

julia> A()
ERROR: MethodError: no method matching A()

But again, I don’t get the point and wouldn’t recommend it :slight_smile:

2 Likes