Parameters.jl strange values in struct coming from dict

I have a struct which I’d like one of the field to come from a dict, so I wrote this code

using Parameters # v0.12.3

const D1 = Dict(
    "a"=>30,
    "b"=>15,
    "c"=>18,
)

@with_kw mutable struct Struct1
    name::String
    dval ::Int = D1[name]
    Struct1(name) = new(name)
end

Now, I initialise my stuct for “a” with

julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 0

I’m not sure where zero comes from,

if I try a few more times I get
julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 5


julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 4


julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 14


julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 0


julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 -1152921504606846976


julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 11088370896

And checking D1 makes sense

julia> D1["a"]
30

I think I’m doing something fundamentally wrong, but I’m unsure what? How can I use D1 to set the dval?

Edit1:

This doesn’t seem to be an issue for dict, fixed values are also causing me problems

julia> @with_kw mutable struct Struct1
           name::String
           dval ::Int = D1[name]
           x::Bool=true
           Struct1(name) = new(name)
       end
Struct1

julia> Struct1("a")
Struct1
  name: String "a"
  dval: Int64 2
  x: Bool false

The inner constructor overrides the default constructor, such as the one created by @with_kw, I believe.

Using an outer constructor instead should work:

@with_kw mutable struct Struct1
    name::String
    dval ::Int = D1[name]
end
 Struct1(name) = Struct1(;name)

Note that I have essentially defined an additional constructor, which calls the original one

1 Like

Yes, it seems that’s correct. Embarrassingly, I think I’ve come across this before. The lack of warning does make it somewhat confusing.