How to assign tuples to struct?

Hi everyone, I struggle with this issue.

Let say I have a tuple of 5 elements,

a = (100, 50, 0.05, 0.05, false, true)

and a struct is defined as,

struct PortfolioInfo
    num_stock::Int64
    num_rndreturn::Int64
    theta::Float64
    epsilon::Float64 
    norm1_constr::Bool
    norm2_constr::Bool
end

My question is, how could I assign the tuple to my struct?

x=PortfolioInfo(a...) should work. The ... syntax is called splatting.

6 Likes

@Oscar_Smith is correct, here’s an example, with an attempt at a non-splatted assignment just to show it doesn’t work.

julia> struct Foo a::Int
       b::Float64
       c::Bool
       end

julia> x=(1, 1.0, false)
(1, 1.0, false)

julia> Foo(x)
ERROR: MethodError: no method matching Foo(::Tuple{Int64,Float64,Bool})
Closest candidates are:
  Foo(::Any, ::Any, ::Any) at REPL[1]:1
  Foo(::Int64, ::Float64, ::Bool) at REPL[1]:1
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> Foo(x...)
Foo(1, 1.0, false)

It worked, I did not notice the splatting syntax. Thanks for your help @purplishrock @Oscar_Smith