Home > Net >  Golang for loop with multiple brackets
Golang for loop with multiple brackets

Time:08-21

I've stumbled upon this repository,

https://github.com/prometheus-community/jiralert/blob/a0f0e80e575e71cbf7db565d3296a3a984282dff/pkg/config/config_test.go#L148

The for loop has multiple brackets:

for _, test := range []struct {
        missingField string
        errorMessage string
    }{
        {"Name", "missing name for receiver"},
    (...)
    } {

        fields := removeFromStrSlice(mandatory, test.missingField)

    (...)
        }
        configErrorTestRunner(t, config, test.errorMessage)
    }

I haven't been able to find anything about this in the go documentation, what is this construct?

CodePudding user response:

The first bracket pair is part of the struct type definition.

The second pair is part of the composite literal value, creating a value for the slice of this struct. The inner, embedded brackets are part of the composite literals creating the struct values of the slice.

The third pair defines the block of the for statement. The for statement iterates over the elements of the slice defined by the mentioned composite literal.

  • Related