英文:
Using the gofmt refactoring tool to rename a global variable
问题
我正在尝试使用gofmt
工具根据这篇博客文章来重构基于Go的代码,我有一个简单的示例:
package main
import (
"fmt"
)
var v = 12
func main() {
fmt.Println(v)
}
我试图将变量v
重命名为m
,并应用以下命令:
gofmt -r 'v -> m' -w main.go
重构后的代码看起来是这样的(有问题):
package m
import (
"fmt"
)
var m = m
func m() {
m
}
我在这里漏掉了什么?
英文:
I'm experimenting the gofmt
tool capabilities for refactoring [tag:go] code based on this blog post, I have this trivial example:
package main
import (
"fmt"
)
var v = 12
func main() {
fmt.Println(v)
}
I'm trying to rename the v
variable to m
applying this recipe:
gofmt -r 'v -> m' -w main.go
The code after the refactoring looks (broken) like:
package m
import (
"fmt"
)
var m = m
func m() {
m
}
What am I missing here?
答案1
得分: 17
你尝试的方法存在问题,gofmt手册中有说明:
使用-r标志指定的重写规则必须是以下形式的字符串:
pattern -> replacement
pattern和replacement都必须是有效的Go表达式。在pattern中,单个小写字母标识符用作通配符,匹配任意子表达式;这些表达式将被替换为replacement中的相同标识符。
(已添加强调)
如果你有var vee = 12
并使用-r vee -> foo
,一切都会正常。但是,使用v -> m
时,v -> m
会匹配每个Go表达式,将其标识为v
并用m
替换。
英文:
There is a problem with what you're trying, the gofmt manual states:
>The rewrite rule specified with the -r flag must be a string of the form:
>
> pattern -> replacement
>
>Both pattern and replacement must be valid Go expressions. In the pattern, single-character lowercase >identifiers serve as wildcards matching arbitrary sub-expressions; those expressions will be substituted for the same identifiers in the replacement.
(highlighting added)
If you had var vee = 12
and used -r vee -> foo
everything would be fine. With v -> m
however,
v -> m
matches every Go expression, identifies it as v
and replaces it by m
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论