#2834·xgo

建议:自动 Lambda 控制流语义

作者: xushiwei创建于 2026年8月11日更新于 2026年8月14日
标签proposalProposal-AcceptedFullSpec

背景 考虑一个使用 repeatUntil(一个支持 Auto-Lambda 的命令)来循环直到某个条件成立的函数 foo:

go
func foo(...) (T1, T2, ...) {
	x := 0
	repeatUntil x > 10 {
		x = modify(x)
		if cond1(x) {
			break        // "break out of the repeatUntil"?
		}
		if cond2(x) {
			continue     // "skip to the next repeatUntil iteration"?
		}
		if cond3(x) {
			return v1, v2, ...   // "return from foo, not from the block"?
		}
	}
	return ...
}

Auto Lambda 允许将 repeatUntil x > 10 { ... } 编写为不使用 =>,但传递给 repeatUntil 的块并没有实际被内联到 foo 中 — 它被编译为一个普通的 Go 闭包,并作为函数值传递给 repeatUntil 的实现。Go 的 breakcontinuereturn 都在最近的闭包中进行语义上作用域限定,因此 作为闭包,这些关键字都无法实现用户在阅读上述代码时所期望的行为。