"Unsafe" inner constructors of parametric types

I’ve recently learned that you can create functions inside a struct definition other than the inner constructor. One use is to create “unsafe” inner constructors, as discussed here: Bypass inner constructor / call `new` outside inner constructor - #4 by Dan

This seems to work fine when the unsafe inner constructor doesn’t have any type parameters. But using type parameters results in an error:

julia> struct Foo{T}
       x::T
       global function unsafe_Foo{T}(x) where {T}
       new{T}(x)
       end
       end
ERROR: UndefVarError: `unsafe_Foo` not defined in `Main`
Suggestion: add an appropriate import or assignment. This global was declared but not assigned.
Stacktrace:
 [1] top-level scope
   @ REPL[1]:1

Any thoughts on what is going on here? Thanks!

You cannot parametrize function names like this. What happens when you define a function for a parametrized type like Foo{T} is that you’re not actually defining a function, but adding a method to the type object Foo{T}. Since there is no parametrized type unsafe_Foo, you cannot add a method to it.

2 Likes

Relevant section in docs: Constructors are just callable objects.