Look at the below two code snippets:
code1:
func getIntJ1() (j int32) {
for {
j = 20
return
}
}
code2:
func getIntJ2() (j int32) {
for true {
j = 20
return
}
}
Playground : https://play.golang.org/p/ZnwjZDksZhu
I think they should print the same value 20
in the console, but they can't do what I want.
The code1
could print value 20
in the console, but the code2
occurs compile error: missing return at end of function
.
All of them have an infinite loop
in the function, why they display in different result?
To prevent functions from running off the end without returning their return value, Go has a concept of a terminating statement. Terminating statements are certain types of statements where it can easily be shown that execution will not continue past that statement. A function with result parameters must end in a terminating statement.
A for
with no break
and no loop condition counts as a terminating statement, but a for
with a loop condition doesn't count, even if that loop condition is always true. (The rules could be expanded to count a for
with true
as its condition as a terminating statement, but adding too many cases makes the definition more confusing than useful.) Your second getIntJ
definition has no terminating statement.
As instructed, insert the return.
package main
import (
"fmt"
)
func main() {
fmt.Println(getIntJ1())
fmt.Println(getIntJ2())
}
func getIntJ1() (j int32) {
for {
j = 20
if j == 21 {
continue
}
return
}
}
func getIntJ2() (j int32) {
for true {
j = 20
if j == 21 {
continue
}
return
}
return
}
Playground: https://play.golang.org/p/QbYQ6NkOMpQ
Output:
20
20
For getIntJ1
, for {}
, the return
is never needed. For getIntJ2
, for condition {}
, the return
may be needed. The compiler could be smarter when condition
is true
It's more idiomatic to write for {}
rather than for true {}
.