Can struct splat field values?

struct  A
  foo : Int32
  bar : String
end

a = A.new

foo, _  = a  #?

Perhaps JSON::Serializable ?

No, this isn’t a thing. If you really want it, could do something like this tho:

struct  A
  foo : Int32
  bar : String

  def splat
    {@foo, @bar}
  end
end

a = A.new

foo, _  = a.splat

Maybe could add some def_splat macro to handle it for you as well.

1 Like

Not really an answer to your question, but how’s that simpler than a.foo ?

struct  A
  property foo : Int32
  property bar : String
  
  def initialize( @foo, @bar )
  end
end

a = A.new( 123, "abc" )
foo = a.foo

It can be defined for any struct quite easily: Carcin

The key part:

struct Struct
  def splat
    {% begin %}
      {
        {% for i in @type.instance_vars %}  @{{i.name}}, {% end %}
      }
    {% end %}
  end
end
1 Like

I’d be careful about suggesting such a generic implementation. For splatting, the order of elements is crucial. So I think it’s best to declare it explicitly instead of relying on the implicit ordering of @type.instance_vars.

:laughing: you’re totally right. I couldn’t help in solving the problem without much consideration. Still, for simpler structs this might work well. But yeah, Blacksmoke16’s alternative of a macro in which the order is explicit makes more sense.