typesconstructorjuliadefault-valueparametric-polymorphism

How to make constructors that create default values for the parametrically typed fields


For a type with parametrically typed fields like:

struct Point{T <: AbstractFloat}
    x::T
    y::T
end

How to make an outer constructor that creates default values with the desired types? For example, I want Point() which takes no arguments to create Point{T}(0.0, 0.0), where I can still specify T as Float64 or other types by some way.


Solution

  • Does this do what you want?

    julia> struct Point{T <: AbstractFloat}
               x::T
               y::T
           end
    
    julia> Point{T}() where T = Point{T}(zero(T), zero(T))
    
    julia> Point{Float64}()
    Point{Float64}(0.0, 0.0)
    
    julia> Point{Float32}()
    Point{Float32}(0.0f0, 0.0f0)
    
    julia> Point{Float16}()
    Point{Float16}(Float16(0.0), Float16(0.0))