I agree with @robert. The compiler cannot guarantee that the function will always return a value. Even though we can see that the loop will eventually *return i* value, the compiler isn't able to make this determination statically.
Compile doesn't complain about the following code. I'm no expert, but I think this is strictly compiler behavior: func myfunc() int { for i := 0; ; i++ { if i > 8 { return i } } } But the following code will not compile. func myfunc() int { for i := 0; <= 8; i++ { if i > 8 { return i } } } To fix that (for didactic purposes only), we can add a return statement after the loop (which will never be reached, but satisfies the compiler): func myfunc() int { for i := 0; true; i++ { if i > 8 { return i } } return 0 // This line is unreachable but satisfies the compiler } If anyone knows more about this behavior, I would be happy to learn more. Cleberson Em sexta-feira, 11 de outubro de 2024 às 19:34:46 UTC-3, Ian Lance Taylor escreveu: > On Fri, Oct 11, 2024 at 3:07 PM robert engels <ren...@ix.netcom.com> > wrote: > > > > true is an expression, the compiler doesn’t inspect that it is a > constant expression, thus you need the return statement > > The exact rules can be seen at > https://go.dev/ref/spec#Terminating_statements. > > Ian > > > > > > On Oct 11, 2024, at 4:57 PM, Pierpaolo Bernardi <olop...@gmail.com> > wrote: > > > > > > Hello, > > > > > > the following code works as I expect: > https://go.dev/play/p/pjKqpZyTU0d > > > > > > However, if I change line 15 from > > > > > > for i := 0; ; i++ { > > > > > > to > > > > > > for i := 0; true; i++ { > > > > > > it does not compile. In my understanding the two should be equivalent, > > > but they are not. Maybe I'm missing a simple explanation? > > > > > > -- > > > 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...@googlegroups.com. > > > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/CANY8u7F3pV_FX3jQHRz%2BOpmrPN0qb6-2-NAwzQYNRe9Qq18D8A%40mail.gmail.com > . > > > > -- > > 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...@googlegroups.com. > > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/0E9E12CB-EF17-4977-BA5A-07704C01DAB9%40ix.netcom.com > . > -- 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/42df00e0-b684-4201-850f-dec90f44ded4n%40googlegroups.com.