There is a flip side to that: if you add the return statements, then ForLoop1() gives an error due to unreachable code! https://play.golang.org/p/0bajnJWTz7U
So you can't win either way. I think this implies that if the behaviour were changed now, it would break the go compatibility promise. On Friday, 5 March 2021 at 04:05:35 UTC peterGo wrote: > Another way to look at it. > > The Go Programming Language Specification > https://golang.org/ref/spec > > For statements > > For statements with for clause > > ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . > > Any element of the ForClause may be empty but the semicolons are required > unless there is only a condition. > > If the condition is absent, it is equivalent to the boolean value true. > > However, the compiler does not appear to apply the equivalency: > > // no error > func ForLoop1() int { > for i := 0; ; i++ { > if i%123 == 0 { > return 456 > } > } > } > > // error: missing return at end of function > func ForLoop2() int { > for i := 0; true; i++ { > if i%123 == 0 { > return 456 > } > } > } > > https://play.golang.org/p/Q-hF7ZhL4Vf > > Peter > > On Thursday, March 4, 2021 at 8:36:07 PM UTC-5 Scott Pakin wrote: > >> The Go compiler (I'm using go1.16 linux/amd64) correctly infers that >> function with an infinite for { … } loop that conditionally returns a >> value from within the loop does not also need to return a value at the end >> of the function: >> >> - https://play.golang.org/p/07ZjFx2uJlx >> >> However, changing that infinite loop to a three-clause for loop with true >> as the continuation condition (e.g., for i := 0; true; i++ { … }) >> complains about a missing return at end of function: >> >> - https://play.golang.org/p/yf4ihkdBUXZ >> >> Shouldn't the compiler treat those two cases the same? >> > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/922d6c8f-9ea9-4067-ba24-5a5afdfbe4f4n%40googlegroups.com.