Go-tools: simple: check against unnecessary parentheses

Created on 3 Feb 2021  路  4Comments  路  Source: dominikh/go-tools

This one is a bit weird, but in one project I work on I've seen code like this:

if v := (mapOfStrings)["key"]; v == "" {
        (mapOfStrings)["key"] = "default_value"
}

That is, mapOfStrings, which is just a map, is put into parentheses. I don't know if it's a copypaste quirk, or if the previous developer thought that there could be some syntax ambiguities, or if they thought that this will be consistent with the code like:

if v := (*ptrToMapOfStrings)["key"]; v == "" {
        (*ptrToMapOfStrings)["key"] = "default_value"
}

Which is also present in the file. But either way this seems a bit silly.

https://play.golang.org/p/Ei5xfwNsDso

needs-decision new-check

All 4 comments

I have seen similar things in math where unnecessary parentheses are used even though order of operations will make it work without it. Take num := (5 * 7) + 5 and num2 := (num / 5) + (2 * num) for example.

This feels like something that would be better placed in gofumpt, to be fixed automatically. /cc @mvdan

Indeed, this kind of syntactic cleanup fits a formatter pretty well :) I filed https://github.com/mvdan/gofumpt/issues/44 for this same issue last year.

I see, thanks. I'm already using Daniel's gofumpt with --extra on the project where this code is from, so if he is already considering implementing that, then this issue can probably be closed.

Was this page helpful?
0 / 5 - 0 ratings