英文:
vim-go deleting unused code when write to disk
问题
我已经将几个包导入到我正在编写的Go包(package commands)的文件中(按照golang教程的步骤进行),我使用的是带有Vim-Go插件的Vim编辑器。其中有几个包目前还没有在该包中使用。当我保存文件 :w 时,Vim似乎会删除未使用的包,这真的很烦人,因为这些未使用的包将会被使用,我只是还没有为它们添加必要的代码。有没有办法在Vim-Go中关闭这个功能,或者我必须删除整个插件才能摆脱这个烦人的行为?
保存之前:
package commands
import (
"fmt"
"os"
"time"
rss "github.com/jteeuwen/go-pkg-rss"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
保存之后:
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
英文:
I have imported several packages into a file in a Go package (package commands) I am writing (following along with a golang tutorial) using Vim with the Vim-Go plugin. Several of these packages are not yet used in the package. When I save the file :w, Vim seems to be deleting the unused packages, which is really annoying because those unused packages are going to be used. I just haven't added the necessary code for them. Is there a way to turn off this functionality in Vim-Go or do I have to delete the whole plugin to get rid of this annoying behavior?
Before Write
package commands
import (
"fmt"
"os"
"time"
rss "github.com/jteeuwen/go-pkg-rss"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
After Save
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
答案1
得分: 5
这是因为你在格式化Go代码时使用了goimports工具(我认为vim-go默认使用它,并且默认在保存时格式化代码)。goimports会自动删除未使用的导入包,这就是它的优点所在。你会在某个时候喜欢上它的 ![]()
目前,你想要使用的是gofmt来格式化代码,它不会处理导入包,只会格式化代码。你可以在.vimrc文件中添加以下内容:
let g:go_fmt_command = "gofmt"
如果你决定在上述操作完成后手动运行goimports来处理文件,你可以运行:GoImports命令。
如果你愿意,你也可以选择另一个选项:通过在.vimrc文件中添加以下内容来关闭保存时的自动格式化功能:
let g:go_fmt_autosave = 0
这样,你仍然可以在格式化代码时使用goimports,但它不会自动在保存时进行格式化。
英文:
This is because you're using goimports as the tool to use when formatting your go code (I think vim-go does this by default - and it formats code on save by default). goimports removes unused imports for you .. thats why its so great. You will learn to love it at some point ![]()
For now, what you want to use is gofmt to format your code, which doesn't touch imports - it only formats the code. You can put this in your .vimrc:
let g:go_fmt_command = "gofmt"
If you decide you want to manually run goimports on your file after you've done the above .. you can run :GoImports.
You can also choose another option if you prefer: you can turn off formatting on save by putting this into your .vimrc:
let g:go_fmt_autosave = 0
Then, you can still use goimports when formatting your code .. but it won't do it automatically on save.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论