I’m currently working with a dictionary whose keys are instances of a custom struct named MyStruct
. Here is the definition:
struct MyStruct
a::Int
b::String
end
I need to use the TOML.print
function to print this dictionary in a TOML-compatible format. When I print a Dict
where MyStruct
is the value, like the example below, everything works fine:
TOML.print(Dict("foo" => MyStruct(5, "bar"))) do x
x isa MyStruct && return [x.a, x.b]
error("unhandled type $(typeof(x))")
end
However, I’m struggling to adapt this approach for a dictionary where MyStruct
instances are used as keys. I understand that TOML doesn’t natively support composite types like my custom struct as keys, so I’m looking for a workaround or a best practice to follow.
dict = Dict(MyStruct(1, "one") => "value1", MyStruct(2, "two") => "value2")
julia> dict = Dict(MyStruct(1, "one") => "value1", MyStruct(2, "two") => "value2")
Dict{MyStruct, String} with 2 entries:
MyStruct(2, "two") => "value2"
MyStruct(1, "one") => "value1"
julia> TOML.print(dict) do x
x isa MyStruct && return Dict("x" => x.x, "y" => x.y)
end
ERROR: MethodError: no method matching String(::MyStruct)
Closest candidates are:
String(::String)
@ Core boot.jl:360
String(::Core.Compiler.LazyString)
@ Core strings/lazy.jl:80
String(::LazyString)
@ Base strings/lazy.jl:80
...
Stacktrace:
[1] print_table(f::var"#7#8", io::Base.TTY, a::Dict{MyStruct, String}, ks::Vector{String}; indent::Int64, first_block::Bool, sorted::Bool, by::Function)
@ TOML.Internals.Printer ~/.asdf/installs/julia/1.9.1/share/julia/stdlib/v1.9/TOML/src/print.jl:152
[2] print_table (repeats 2 times)
@ ~/.asdf/installs/julia/1.9.1/share/julia/stdlib/v1.9/TOML/src/print.jl:131 [inlined]
[3] #print#6
@ ~/.asdf/installs/julia/1.9.1/share/julia/stdlib/v1.9/TOML/src/print.jl:204 [inlined]
[4] print(f::var"#7#8", a::Dict{MyStruct, String}; sorted::Bool, by::Function)
@ TOML.Internals.Printer ~/.asdf/installs/julia/1.9.1/share/julia/stdlib/v1.9/TOML/src/print.jl:205
[5] print(f::var"#7#8", a::Dict{MyStruct, String})
@ TOML.Internals.Printer ~/.asdf/installs/julia/1.9.1/share/julia/stdlib/v1.9/TOML/src/print.jl:205
[6] top-level scope
@ REPL[6]:1
Does anyone have suggestions on how I might achieve this? Any help would be appreciated!