0

I have a struct such as

type Info struct {
    Foo         string
    FooBar      string
    Services    string
    Clown       string
}

and lets say I have already populated the first 2 fields

input := &Info{
   Foo: "true",
   Services: "Massage",
}

Is there a way to "reopen" the struct to add missing elements. Something like this :

input = {
   input,
   Foobar: "Spaghetti",
   Clown: "Carroussel"
}

Instead of

input.Foobar = "Spaghetti"
input.Clown = "Carroussel"

I have multiple fields and just don't really like having many lines input.Fields. I didn't find anything like it. So I was wondering.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 2
    In general: Go has no syntactic sugar. If something hasn't been covered in the Tour of Go it's not there. – Volker Feb 26 '21 at 14:33
  • You've already found the simple, obvious and correct solution. Just settle for that, even if it isn't as beautiful as the code of your dreams. – Hymns For Disco Feb 26 '21 at 19:33

1 Answers1

3

No, this is not supported by the language's syntax.

Btw, the solution you want to avoid consists of less lines that the theoretical alternative :) (2 lines vs 4 lines in your example).

One could create a helper function which copies non-zero fields from one instance of a struct to another, so you could create a struct with the additional fields using a composite literal and use that as the source, but this requires using reflection, which is slow, and this solution wouldn't be more readable.

See related: "Merge" fields two structs of same type

icza
  • 389,944
  • 63
  • 907
  • 827