使用gofmt重构工具来重命名全局变量。

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

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 mapplying 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.

huangapple
  • 本文由 发表于 2014年2月11日 22:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/21705172.html
匿名

发表评论

匿名网友

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

确定