Struct constructors with partial types

From the docs about composite types:

Two constructors are generated automatically (these are called default constructors ). One accepts any arguments and calls convert to convert them to the types of the fields, and the other accepts arguments that match the field types exactly.

These two default constructors are MyStruct(x,y) and MyStruct{A,B}(x,y).

You can add your missing constructor by defining it afterwards:

struct MyStruct{A,B}
       x::A
       y::B
end
MyStruct{A}(x, y) where A = MyStruct(convert(A, x), y)

Alternatively, you can opt-out of having the two default constructors by defining inner constructors.

struct MyStruct{A,B}
       x::A
       y::B
       MyStruct{A}(x, y) where A = MyStruct(convert(A, x), y)
end

Now, there is only the one constructor.

2 Likes