Getting syntax-error on from assignment in if statements

188 views
Skip to first unread message

Ariel Mashraki

unread,
Oct 15, 2020, 10:24:34 AM10/15/20
to golang-nuts
Giving these 2 statements (in main function), the first passes and the second causes a parse-error.

type T struct{}
func (T) F() bool { return true } 

func main() {
v := T{}.F() // works
if v := T{}.F(); v {} // syntax error: cannot use v := T as value
}

I went over the grammar rules of the "If Statement" and it contains a "SimpleStatement". The "SimpleStatement" contains the same "Assignment" rule that is used for general assignments. The first works, but the second fails. Any thoughts what's the difference between the 2 assignments?  

I can overcome this by just using "if v := (T{}).F()", but curious to know the reason. 

Thanks
 

Brian Candler

unread,
Oct 15, 2020, 11:16:40 AM10/15/20
to golang-nuts
It looks like a parsing ambiguity to me.  The error suggests that the open-brace is being treated as the start of the body of the if-statement, i.e.

if v := T {
}.F()

Try changing it to

if v == T{}.F(); v {}

and you'll get a different error: "syntax error: unexpected . at end of statement"

Ian Davis

unread,
Oct 15, 2020, 11:42:33 AM10/15/20
to golan...@googlegroups.com
It is a parsing ambiguity and is mentioned in the specification towards the end of https://golang.org/ref/spec#Composite_literals


Ariel Mashraki

unread,
Oct 15, 2020, 6:23:14 PM10/15/20
to golang-nuts
Good to know that.

Thanks for your response Ian. 

Reply all
Reply to author
Forward
0 new messages