英文:
no-op/explicitly do nothing in go
问题
我有一个类型方法,可以改变类型的字段。它不接受任何参数,也不返回任何值。该方法的主要部分是一个switch
块。我想要能够在switch
块中使用一个空操作来“短路”退出。在将其重构为类型方法之前,我可能会直接从函数中返回,但那样不行。删除该case
将破坏方法的逻辑——default
情况会改变状态,如果匹配到该情况,我不想这样做。我需要类似于Python中的pass
的功能。
代码:
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
}
}
请注意,我只翻译了代码部分,其他内容不包括在内。
英文:
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展开收缩 = new(Section)
buffer.Reset()
return state, nil
}
}
}
答案1
得分: 31
与其他语言不同,在Go语言中,控制流在每个case
语句处中断,除非使用fallthrough
语句明确要求控制流进入下一个case
。
而且,在case
之后不需要必须有语句(可以为空)。看下面的例子:
i := 3
switch i {
case 3:
case 0:
fmt.Println("Hello, playground")
}
即使i==3
并且在case 3
之后没有语句,它也不会打印任何内容。
与此类似的是:
i := 3
switch {
case i == 3:
case i == 0:
fmt.Println("Hello, playground")
}
在Go Playground上尝试一下。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论