# Reading structs from binary stream

**URL:** https://discourse.julialang.org/t/reading-structs-from-binary-stream/33854
**Category:** General Usage
**Tags:** binaryio
**Created:** [January 27, 2020, 3:13pm UTC](https://discourse.julialang.org/t/reading-structs-from-binary-stream/33854 "2020-01-27T15:13:20Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Mikhail\_Kagalenko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikhail_kagalenko/32/13257_2.png) [@Mikhail\_Kagalenko](https://discourse.julialang.org/u/Mikhail_Kagalenko)
#### Post date: [January 27, 2020, 3:13pm UTC](https://discourse.julialang.org/t/reading-structs-from-binary-stream/33854/1 "2020-01-27T15:13:20Z")

</div>

What is the up-to-date, idiomatic method of deserializing a stream of un-padded binary values from an external source into Julia struct?

StrPack.jl carries a big warning that it is not actively maintained.

---

<div class="post-metadata">

### Author: ![Mikhail\_Kagalenko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikhail_kagalenko/32/13257_2.png) [@Mikhail\_Kagalenko](https://discourse.julialang.org/u/Mikhail_Kagalenko)
#### Post date: [January 28, 2020, 10:01pm UTC](https://discourse.julialang.org/t/reading-structs-from-binary-stream/33854/2 "2020-01-28T22:01:07Z")

</div>

So far the best solution that I found looks like this:

```julia
function Base.read(io::IO, strc_t::Union{Type{S1},
                                        Type{S2},
                                        Type{S3}})
    fn = fieldnames(strc_t)
    vals = Vector{Any}(undef, length(fn))
    for (n, f) in enumerate(fn)
        vals[n] = read(io, fieldtype(strc_t, f))
    end
    return strc_t(vals...)
end

function Base.write(io::IO, strc::Union{S1, S2, S3})
    sum([write(io, getfield(strc, f)) 
        for f in fieldnames(typeof(strc))])
end

```

That should work for scenario where types are like this

```julia
struct S1
  a::Int8
  b::UInt16
...
end

struct S2
  c::Float64
  d::Int
...
end

struct S3
   x::S1
   y::S2
end

```

Criticisms are welcome.

(By the way, I was surprised that there is no default write method for tuples, why is that?)
