Combined declaration of multiple variables of the same type?

Is it possible to declare multiple variables of the same type in a C-style in Julia? I like to define a struct as this:

struct Tbp
  es::Float64
  ep::Float64
  vsss::Float64
  vsps::Float64
  vpps::Float64
  vppp::Float64
  n::Int
  nc::Float64
  rc::Float64
  r0::Float64
  r1::Float64
  phi0::Float64
  m::Float64
  mc::Float64
  dc::Float64
  d0::Float64
  d1::Float64
end

in one line like this

struct Tbp
   es, ep, vsss, ... :: Float64
end

No. But you could define a macro to do this.

1 Like

You can make this simultaneously easier to write and to read and more generic as follows:

julia> struct MyType{T}
       a::T
       b::T
       c::T
       d::Int
       end

julia> MyType(3.1, 4.2, 5.3, 17)
MyType{Float64}(3.1, 4.2, 5.3, 17)
1 Like

Sure, this is more elegant than the original code, but still, one must repeat the ::T all the time. To me, what I want seems a reasonable feature request for future versions of Julia, isn’t it?

No need to wait, as Mauro said you can do it already with a macro. (And check out his related package Parameters.jl.) And I doubt it would be included in the next version of Julia.

Often having so many variables in a type would be a sign that you need to redesign.

1 Like
julia> macro TTime(T, vars...)
           expr = Expr(:block)
           append!(expr.args, map(var -> :($var::$T), vars))
           return esc(expr)
       end
@TTime (macro with 1 method)

julia> struct MyType{T}
           @TTime T x y z
       end

julia> MyType(1,2,3)
MyType{Int64}(1, 2, 3)

julia> fieldnames(MyType)
(:x, :y, :z)
6 Likes

Many thanks, that is really nice.

2 Likes

That’s a beautifully simple solution!

1 Like