Function or struct?

struct MyType{T} 
    label::T
    x::Float64 
    y::Float64  
end
function MyType(; label = 1000,  x = 0, y = 0)
    return MyType(label, x, y)
end

I am a bit confused. Here we have a function and a struct, both of which are named ‘MyType’. They both are associated with the () bracekts. How can I tell which is invoked? For example, in the line

return MyType(label, x, y)

It should be invoking the struct, right?

In this specific case, we can differentiate the two by the ; symbol, but what if in the definition of the function, the ; is omitted?

The struct implicitly defines a constructor function which just takes a positional argument for each field. You now defined another method for construction. This simply multiple dispatch. I encourage you to read more on constructors in the manual.

I also want to point out that in many programming languages you call the type/class to construct an instance (cf. Python) so Julia isn’t special in that regard. The new thing is that multiple dispatch allows you to simply add new nethods to the constructor.

6 Likes

The ; symbol just separates positional arguments from keyword arguments (there’s no such thing as arguments that can be passed by either position or keyword). The values assigned to the keywords aren’t what make them keywords, those are just default values, though it’s more common for keywords to have default values.

2 Likes

Just to add a bit of clarification to the other excellent answers: technically, the struct is never “invoked”, its inner constructor may be invoked. People usually do not distinguish the two since structs define an inner constructor so they can be used interchangeably, but nevertheless they are different concepts.

You can list them all constructors (inner and outer) with methods(MyType). The one matching the method signature will be invoked.

1 Like