No-op / obviously do nothing

I have a type method that mutates type fields. It takes no arguments and returns nothing. The main part of the method is a block switch

. I want to be able to short-circuit out of a block switch

using no-op. Before I reworked it into a type method, I would just return from the function, but it isn't. Removing a case will break the logic of the method - the case default

changes state, which I don't want to do if that case is consistent. I want a Python equivalent 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
        }
    }
}

      

+3


source to share


1 answer


Unlike other languages, in Go, the flow of control is interrupted at every case

statement switch

, control does not flow to the next case

, unless it is explicitly set with fallthrough

.

And also the instruction is not required after case

(it can be empty). See this example:

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

      

It won't print anything, even if there is no instruction i==3

after case 3

.



The same as:

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

      

Try it on the Go Playground .

+8


source







All Articles