Decomposing struct in function argument

is it possible to to something like this?

struct X
    a
    b
end

f((a,b)::X) = a+b

Yes, with property destructuring (i.e. (; ...) syntax):

julia> struct X; a; b; end

julia> f((; a,b)::X) = a+b
f (generic function with 1 method)

julia> f(X(1,2))
3
5 Likes

These work.

 (a,b)  = [1,2]      #tuple  (un-named )
  a,b   = [1,2]      #individual variables 

but not this

(;a,b)  = [1,2]

Is it possible to put a vector into a NamedTuple like this ?

What would be the expected result?

For consistency (; a, b) = ... should always assign to variable a and b… If you want to create a NamedTuple from a vector, here are a few ways:

NamedTuple{(:a,:b)}([1,2])

NamedTuple((:a,:b) .=> [1,2])

(; ((:a,:b) .=> [1,2])...)

@NamedTuple{a::Int, b::Int}([1,2])   # to choose field types explicitly
3 Likes

Thanks :slight_smile: