Position of type definition in struct with default values

I’d like to define a struct containing field variables with default values. Am I right in assuming there is no difference between

import Parameters: @with_kw

@with_kw struct S
       d::Dict{Int,Int} = Dict()
end

and

@with_kw struct T
       d = Dict{Int,Int}()
end

?

In both cases, we get

julia> S()
S
  d: Dict{Int64, Int64}

and

julia> T()
T
  d: Dict{Int64, Int64}

, respectively.

Which of the two definitions should be preferred? Thanks a lot!

The d in T is not annotated, thus it can be any type according to initialization.

1 Like

As you use it there is no difference, but here is an example where you can see how it would matter

julia> test = Dict(:A => 1, :B => 4)
Dict{Symbol, Int64} with 2 entries:
  :A => 1
  :B => 4

julia> S(test)
ERROR: MethodError: Cannot `convert` an object of type Symbol to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::Ptr) where T<:Integer at ~/git/julia/usr/share/julia/base/pointer.jl:23
  convert(::Type{T}, ::T) where T<:Number at ~/git/julia/usr/share/julia/base/number.jl:6
  convert(::Type{T}, ::Number) where T<:Number at ~/git/julia/usr/share/julia/base/number.jl:7
  ...
Stacktrace:
 [1] setindex!(h::Dict{Int64, Int64}, v0::Int64, key0::Symbol)
   @ Base ./dict.jl:373
 [2] Dict{Int64, Int64}(kv::Dict{Symbol, Int64})
   @ Base ./dict.jl:104
 [3] convert
   @ ./abstractdict.jl:525 [inlined]
 [4] S(d::Dict{Symbol, Int64})
   @ Main ~/.julia/packages/Parameters/MK0O4/src/Parameters.jl:505
 [5] top-level scope
   @ REPL[11]:1

julia> T(test)
T
  d: Dict{Symbol, Int64}

since T will allow any type, just that the default is the same, but S will not allow any other type. If you know that you always want the field to be Dict{Int,Int} you probably want S.

1 Like