1

I have function that creates a slice like this :

func buildOptions(cfg *ServerConfig) []SomeType {

    return []SomeType{
        Option1,
        Option2,
        Option3,
    }
}

I need Option3 to be added to the slice only if a certain condition is met. Can it be done with some kind of immediate if in the same statement?

of do I have to do something like this:

func buildOptions(cfg *ServerConfig) []SomeType {

    options:= []SomeType{
        Option1,
        Option2,
    }

    if addOption3==true{
       options = append(options, Option3)
    }
    return options
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
FunkSoulBrother
  • 2,057
  • 18
  • 27

1 Answers1

4

No, you can't have conditional inclusion of listed elements in a composite literal.

And it may be more verbose using an additional if and append(), but it's much more obvious what happens (what your code does).

You could achieve something like this using a helper function passing the condition and all the elements, but that just obfuscates the code more and would have worse performance.

icza
  • 389,944
  • 63
  • 907
  • 827
  • @FunkSoulBrother One could argue about that. Why list a value which you don't want to add? That's obfuscation. Go aims simplicity. Add all kinds of features some find useful, and you'll end up with what Java is today. – icza Jun 21 '19 at 07:58