Compiling error when using struct literal in for loop

95 views
Skip to first unread message

Sheng Yu

unread,
May 27, 2016, 1:10:25 AM5/27/16
to golang-nuts
Hi,

I experienced a weird compiling error in my go program. I have such code snippet to reproduce it:


package main

import "fmt"

type T struct {
Field int
}

func (t T) Next() T {
return T{t.Field+1}
}

func main() {
/* Got error at next for statement:
prog.go:14: syntax error: unexpected { at end of statement
prog.go:17: syntax error: non-declaration statement outside function body

for t := T{1}; t.Field < 10; t = t.Next() {
fmt.Println(t)
} */
// This is fine
t2 := T{1}
for ; t2.Field < 10; t2 = t2.Next() {
fmt.Println(t2)
}
}

I can understand the compiler may consider the first '{' be the beginning of a block. Do we consider it a bug? If the behavior is intentional, can we output less confusing error message?

Thanks.
Sheng

Ian Lance Taylor

unread,
May 27, 2016, 1:23:08 AM5/27/16
to Sheng Yu, golang-nuts
Search for "ambiguity" in https://golang.org/ref/spec#Composite_literals .

You need to write
for t := (T{1}); t.Field < 10; t = t.Next() {

Yes, a better error message would be nice if possible. It's not easy,
though, as the parse failure is pretty far from the code that needs to
change.

Ian

Sheng Yu

unread,
May 31, 2016, 9:21:56 PM5/31/16
to Ian Lance Taylor, golang-nuts
Thanks for the pointer. It's good to have it in the spec already. 

Sheng

Reply all
Reply to author
Forward
0 new messages