goslicecomposite-literals

Can I add items to a slice in the creation statement depending on a condition?


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
}

Solution

  • 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.