Skip to content

Commit

Permalink
Expose grow_to_structarray! as a public API
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Dec 15, 2019
1 parent 7d399b1 commit 6673195
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,38 @@ end
s = [MyType(rand(), a=1, b=2) for i in 1:10]
StructArray(s)
```

## Advanced: mutate-or-widen style accumulation

StructArrays provides `grow_to_structarray!(dest, src)` which works like `append!(dest, src)` if `dest` can contain all element types in `src` iterator; i.e., it _mutates_ `dest` in-place:

```julia
julia> dest = StructVector((a=[1], b=[2]))
1-element StructArray(::Array{Int64,1}, ::Array{Int64,1}) with eltype NamedTuple{(:a, :b),Tuple{Int64,Int64}}:
(a = 1, b = 2)

julia> StructArrays.grow_to_structarray!(dest, [(a = 3, b = 4)])
2-element StructArray(::Array{Int64,1}, ::Array{Int64,1}) with eltype NamedTuple{(:a, :b),Tuple{Int64,Int64}}:
(a = 1, b = 2)
(a = 3, b = 4)

julia> ans === dest
true
```

Unlike `append!`, `grow_to_structarray!` can _widen_ element type of `dest` array element types:

```julia
julia> StructArrays.grow_to_structarray!(dest, [(a = missing, b = 6)])
3-element StructArray(::Array{Union{Missing, Int64},1}, ::Array{Int64,1}) with eltype NamedTuple{(:a, :b),Tuple{Union{Missing, Int64},Int64}}:
NamedTuple{(:a, :b),Tuple{Union{Missing, Int64},Int64}}((1, 2))
NamedTuple{(:a, :b),Tuple{Union{Missing, Int64},Int64}}((3, 4))
NamedTuple{(:a, :b),Tuple{Union{Missing, Int64},Int64}}((missing, 6))

julia> ans === dest
false
```

Since the original array `dest` cannot hold input, notice that a new array is created (`ans !== dest`).

Combined with [function barriers](https://docs.julialang.org/en/latest/manual/performance-tips/#kernel-functions-1), `grow_to_structarray!` is a useful building block for `collect`-like functions.

0 comments on commit 6673195

Please sign in to comment.