Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/gofmt: don't remove spaces when combining binary and unary * #40288

Closed
peidaqi opened this issue Jul 18, 2020 · 3 comments
Closed

cmd/gofmt: don't remove spaces when combining binary and unary * #40288

peidaqi opened this issue Jul 18, 2020 · 3 comments

Comments

@peidaqi
Copy link

peidaqi commented Jul 18, 2020

What version of Go are you using (go version)?

go1.14.4

Problem

I understand that gofmt will try to remove spaces between operator and operand, so that it's easier to tell the association. However, this creates weird situations when the star operator is involved with pointers. For example:

x := 10
p1 := &x
p2 := &x
fmt.Println(10 * *p1 * *p2)

works as expected, but if we add a 1 in the last line:

x := 10
p1 := &x
p2 := &x
fmt.Println(10**p1**p2 + 1)

where the 10 **p1 **p2 would be very easily confused as an exponential operator - which golang doesn't have.

@ianlancetaylor
Copy link
Contributor

CC @griesemer

@ianlancetaylor ianlancetaylor changed the title gofmt shouldn't remove spaces when there's pointer invovled cmd/gofmt: don't remove spaces when combining binary and unary * Jul 19, 2020
@ALTree
Copy link
Member

ALTree commented Jul 19, 2020

This is #2098, in particular see #2098 (comment). At the time, it was closed as WAI.

@griesemer
Copy link
Contributor

If we rewrite your example as desired, we get:

fmt.Println(10 * *p1 * *p2 + 1)

which is better for the multiplications, but worse for the addition as it lost its difference from the multiplications which have higher precedence. As has been pointed out above, this was discussed almost 10 years ago and we decided to leave it alone. The better solution is to introduce parentheses to increase readability when it's problematic. Also, this is not a very common situation.

@golang golang locked and limited conversation to collaborators Jul 19, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants