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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/289daadd-b833-4b04-8d65-b20f8bfec191n%40googlegroups.com.