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: gofmt is inconsistent #24609

Closed
cg31 opened this issue Mar 30, 2018 · 2 comments
Closed

cmd/gofmt: gofmt is inconsistent #24609

cg31 opened this issue Mar 30, 2018 · 2 comments

Comments

@cg31
Copy link

@cg31 cg31 commented Mar 30, 2018

In following code, both functions have argument str, and both functions are called with "test"+str1, go-fmt should have same behavior handling them.

But the first case, there will be spaces inserted around +, in second case, the spaces will be removed around +.

package main

import "fmt"

func test1(str string) {
	fmt.Println(str)
}

func test2(str string, str2 string) {
	fmt.Println(str)
	fmt.Println(str2)
}
func main() {
	str1 := "1"
	str2 := "2"
	test1("test"+str1) // spaces will be inserted around '+'
	test2("test" + str1, str2) // spaces will be removed around '+'
}
@ysmolsky
Copy link
Member

@ysmolsky ysmolsky commented Mar 30, 2018

It's not a bug, but a feature: https://golang.org/doc/effective_go.html#formatting

Parentheses
Go needs fewer parentheses than C and Java: control structures (if, for, switch) do not have parentheses in their syntax. Also, the operator precedence hierarchy is shorter and clearer, so
x<<8 + y<<16
means what the spacing implies, unlike in the other languages.

Check this out: https://play.golang.org/p/JiiUb_kjcXC - it's already properly formatted.

@FiloSottile FiloSottile changed the title go-fmt is inconsistent cmd/gofmt: gofmt is inconsistent Mar 30, 2018
@FiloSottile
Copy link
Member

@FiloSottile FiloSottile commented Mar 30, 2018

This is indeed intended behavior. Just like (5 * 2) has spaces around the *, but adding a + removes them ((5*2 + 2)) to provide visual grouping. Here the , has precedence, so the spaces are removed to provide visual grouping in the arguments.

It gets more useful in cases like ("test"+str1, "test"+str2), where you can clearly see there are two arguments.

@golang golang locked and limited conversation to collaborators Mar 30, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.