Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no-op/explicitly do nothing in go

Tags:

go

I have a type method that mutates the type's fields. It takes no arguments and returns nothing. The bulk of the method is a switch block. I want to be able to "short-circuit" out of the switch block with a no-op. Before I refactored it into a type method, I would've just returned out of the function, but that's out. Removing the case would break the logic of the method--the default case mutates state, which I don't want to do if this case is matched. I need the equivalent of Python's pass, basically.

Code:

func (parser *Parser) endSectionName () {
    state = parser.State
    buffer = parser.buffer
    results = parser.results
    switch {
        case state.HasFlag(IN_ESCAPED) {
            // ???
        }
        case !inSection(state) {
            return state, NotInSectionError
        }
        case !state.HasFlag(IN_SECTION_NAME) {
            state.Reset()
            return state, errors.New("Parsing error: Not in section name")
        }
        default {
            state.RemoveFlag(IN_SECTION_NAME)
            s := buffer.String()
            results[s] = new(Section)
            buffer.Reset()
            return state, nil
        }
    }
}
like image 422
swizzard Avatar asked Apr 21 '15 14:04

swizzard


1 Answers

Unlike in other languages, in Go the control flow breaks at each case of a switch statement, control doesn't flow into the next case unless it is explicitly "asked" for with the fallthrough statement.

And also a statement is not required after the case (it can be empty). See this example:

i := 3
switch i {
case 3:
case 0:
    fmt.Println("Hello, playground")
}

It will print nothing even though i==3 and there is no statement after case 3.

Same as this:

i := 3
switch {
case i == 3:
case i == 0:
    fmt.Println("Hello, playground")
}

Try it on the Go Playground.

like image 107
icza Avatar answered Sep 22 '22 10:09

icza