Skip to content

Feature Request: Round-trip Julia structs via StructUtils.jl #235

Description

@stephenberry

MAT.jl writes arbitrary Julia structs to .mat files but always reads them back as Dict{String, Any}. JSON.jl solves this by letting users provide a target type on read, powered by StructUtils.jl. MAT.jl could do the same.

Example

struct Person
    name::String
    age::Int
end

# Write works today
matwrite("data.mat", Dict("p" => Person("Alice", 30)))

# Today: returns Dict("name" => "Alice", "age" => 30)
# Proposed: returns Person("Alice", 30)
person = matread("data.mat", "p", Person)

This would also support nested structs, default values (@defaults), field renaming (@tags), Union{T, Nothing} fields, and abstract type dispatch via @choosetype (all handled by StructUtils.jl).

Abstract type dispatch with @choosetype

abstract type Animal end
struct Dog <: Animal
    name::String
    breed::String
end
struct Cat <: Animal
    name::String
    indoor::Bool
end

MAT.@choosetype Animal x -> haskey(x, "breed") ? Dog : Cat

struct Household
    owner::String
    pet::Animal
end

household = matread("data.mat", "h", Household)
# Household("Alice", Dog("Rex", "Labrador"))

Implementation

Since MAT.jl already reads structs as Dict{String, Any}, the typed read is a thin wrapper using StructUtils.constructfrom:

function matread(filename, varname, ::Type{T}) where T
    dict = matread(filename)
    return StructUtils.constructfrom(T, dict[varname])
end

PR

Would you be interested in a pull request that adds this support?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions