gofmt重写规则能否删除冗余的参数类型?

huangapple go评论80阅读模式
英文:

can a gofmt rewrite rule remove redundant argument types?

问题

如果你有这样的代码:func MyFunc(a int, b int),可以使用gofmt重写规则将其更改为:func MyFunc(a, b int)

你尝试了:gofmt -r "f(x t, y t) -> f(x, y t)" myfile.go,但是得到了错误:parsing pattern f(x t, y t) at 1:5: expected ')', found 'IDENT' t

你还尝试了:gofmt -r "f(x int, y int) -> f(x, y int)" myfile.go,但是得到了类似的错误,只是将int替换为t。

我已经阅读了gofmt文档,并进行了网络搜索,但没有找到有用的信息。

我故意使用单个字符标识符来匹配表达式。

我怀疑问题可能在于尝试匹配类型,因为它可能不被视为一个"表达式"。

是否可能使用gofmt来实现这个目标?

英文:

If you have code like: func MyFunc(a int, b int)

Can a gofmt rewrite rule change it to: func MyFunc(a, b int)

I tried: gofmt -r "f(x t, y t) -> f(x, y t)" myfile.go

But I get: parsing pattern f(x t, y t) at 1:5: expected ')', found 'IDENT' t

I also tried: gofmt -r "f(x int, y int) -> f(x, y int)" myfile.go

But it gives a similar error for int instead of t

I have read the gofmt documentation. A web search didn't turn up anything helpful.

I am deliberately using single character identifiers to match expressions.

I suspect the problem may be in trying to match the type since it may not be regarded as an "expression"

Is it possible to do this with gofmt?

答案1

得分: 3

不,这是不可能的,因为go fmt将模式视为"Expression",请查看http://golang.org/src/cmd/gofmt/rewrite.go中的parseExpr()函数。

Go规范(http://golang.org/ref/spec#Expressions)明确指出"表达式通过将运算符和函数应用于操作数来指定值的计算"。
所以go fmt尝试将你的模式"f(x t, y t)"解析为函数调用,所以它期望逗号或括号而不是"t"。

你不能编写与"func MyFunc(a int, b int)"相匹配的模式,因为它是函数定义,不是有效的go表达式。

英文:

No, its not possible - because go fmt treat patter as "Expression", look at the http://golang.org/src/cmd/gofmt/rewrite.go parseExpr() function.

Go specification(http://golang.org/ref/spec#Expressions)
clearly says what "An expression specifies the computation of a value by applying operators and functions to operands."
so go fmt try to parse your pattern "f(x t, y t)" as function call, so instead of "t" it expects comma or parentheses.

you can not write pattern which will much "func MyFunc(a int, b int)" - because its function definition, not a valid go expression

huangapple
  • 本文由 发表于 2014年4月5日 01:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/22869017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定