Skip to content

Commit 32248e2

Browse files
author
Pietro Vertechi
authored
added kwarg constructor (JuliaArrays#13)
* added kwarg constructor * test inference
1 parent ec27b66 commit 32248e2

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/structarray.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ StructArray{T}(c::C) where {T, C<:NamedTuple} =
2222
StructArray{createtype(T, eltypes(C)), length(size(c[1])), C}(c)
2323
StructArray(c::C) where {C<:NamedTuple} = StructArray{C}(c)
2424

25+
StructArray{T}(; kwargs...) where {T} = StructArray{T}(values(kwargs))
26+
StructArray(; kwargs...) = StructArray(values(kwargs))
27+
2528
StructArray{T}(args...) where {T} = StructArray{T}(NamedTuple{fields(T)}(args))
2629
@generated function StructArray{T}(::Base.UndefInitializer, d::Integer...) where {T}
2730
ex = Expr(:tuple, [:(Array{$(fieldtype(T, i))}(undef, sz)) for i in 1:fieldcount(T)]...)

test/runtests.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,19 @@ end
2222
@test t3 == t
2323
end
2424

25+
@testset "kwargs constructor" begin
26+
a = [1.2]
27+
b = [2.3]
28+
@test StructArray(a=a, b=b) == StructArray((a=a, b=b))
29+
@test StructArray{ComplexF64}(re=a, im=b) == StructArray{ComplexF64}(a, b)
30+
f1() = StructArray(a=[1.2], b=["test"])
31+
f2() = StructArray{Pair}(first=[1.2], second=["test"])
32+
t1 = @inferred f1()
33+
t2 = @inferred f2()
34+
@test t1 == StructArray((a=[1.2], b=["test"]))
35+
@test t2 == StructArray{Pair}([1.2], ["test"])
36+
end
37+
2538
@testset "complex" begin
2639
a, b = [1 2; 3 4], [4 5; 6 7]
2740
t = StructArray{ComplexF64}(a, b)

0 commit comments

Comments
 (0)