问题
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:
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.
来源:https://stackoverflow.com/questions/26824234/vim-go-deleting-unused-code-when-write-to-disk