0

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?

2 Answers 2

2

The first bracket pair is part of the struct type definition which has the syntax:

struct{
    field1 type1
    field2 type2
    ...
}

The second pair is part of the composite literal value, creating a value for the slice of this struct. It has the syntax of:

[]elementType{value1, value2, ...}

The inner, embedded brackets are part of the composite literals creating the struct values of the slice. The type is omitted (it's known from the slice type), so each {field1Value, fieldValue2...} is a struct value.

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.

Sign up to request clarification or add additional context in comments.

Comments

1

To clean up the code for better readability and understanding. Whatever you gave was equivalent to:

type TestStruct struct {
  missingField string
  errorMessage string
}

testCase := TestStruct {
  {
    missingField: "Name",
    errorMessage: "missing name for receiver",
  }
  (...)
}


for _, test := range(testCase) {

  fields := removeFromStrSlice(mandatory, test.missingField)
}

configErrorTestRunner(t, config, test.errorMessage) is probably from a parent test func

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.