简体   繁体   中英

Goland automatic formatting

Is it possible to tweak how Goland automatically formats, adds, and removes imports? It keeps removing an import that my program needs to function so I need to keep manually re-adding it after every push, and it's driving me nuts.

Also, is it possible to set Goland so that it automatically formats (as in go fmt ) on save?

Is it possible to tweak how Goland automatically formats, adds, and removes imports?

I suspect that this (Git | Commit -> Settings -> Optimize imports ) is the option you are looking for (note that there are a lot of other relevant settings on the referenced page).

Note that unused imports result in a compilation error (eg imported and not used: "net/http" ) so this may be something you want to resolve before checking code in.

Also, is it possible to set Goland so that it automatically formats (as in go fmt) on save?

You can run go fmt on save but there are a number of factors to consider which are covered in this blog post (main consideration is that GoLand has its own formatter). In summary the current state (from the link) is:

Currently, GoLand offers three ways to interact with 'go fmt': dedicated actions, before commit tools, and file watchers.

Under the Tools | Go Tools menu, you can find two actions related to code formatting: Go Fmt File and Go Fmt Project. Each has a shortcut assigned to it: Alt + Shift + Control + F (Alt + Shift + Cmd + F on macOS) and Alt + Shift + Control + P (Alt + Shift + Cmd + P), respectively. The sole purpose of these actions is to run 'go fmt', providing it with either file paths or a path to the project directory, and they only work when you invoke them manually.

There are several hooks that can be run before a commit. They can be configured via Settings (Preferences on macOS) | Version Control | Commit | Before Commit. There you can find Go fmt, which is enabled by default.

The third way is to configure a file watcher. Under Settings (Preferences), you can find Tools | File Watchers. It's easy to add a new watcher by using the predefined 'go fmt' template. Whenever a Go file is changed, the command is executed on it. The key word in this case is “whenever,” as users don't have full control over the precise moment a file gets modified. I'll describe this problem in more detail in the next session.

You should go to File -> Settings -> Tools -> Actions on Save and turn off "Reformat code" and "Optimize imports"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM