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

Viewed 117

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.

2 Answers

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))

If you don't mind adding an additional dependency, the package Parameters.jl provides the macro @with_kw allowing to specify default values in the following way:

using Parameters
@with_kw struct Point{T <: AbstractFloat}
  x::T = 0.0
  y::T = 0.0
end

julia> Point()
Point{Float64}
  x: Float64 0.0
  y: Float64 0.0

julia> Point{Float32}() 
Point{Float32}
  x: Float32 0.0f0
  y: Float32 0.0f0
Related