Refactoring is a regular part of software development. As a Go application grows, developers often need to move declarations between files, add methods to implement interfaces, update struct tags, or change existing code without affecting its behavior.
Many of these changes are straightforward when the required information is already available in the source code. However, some refactoring operations need additional decisions from the developer. For example, when adding struct tags, the developer may need to choose between JSON, YAML, and database tags. When implementing an interface, the developer needs to identify which interface the type should implement.
Traditionally, language servers could offer a refactoring action only when they had enough information to calculate the changes automatically. If additional input was necessary, the developer often had to make the changes manually or use editor-specific extensions.
The Go language server, gopls, has introduced interactive refactoring to address this limitation. It allows the language server to request information from the developer through dialogs inside the editor and then apply the appropriate code changes.
Working support for this capability is available in gopls v0.24.0 and the official Go extension for Visual Studio Code v0.56.0.
This article explains how interactive refactoring works, how to use it for common Go development tasks, and how it can reduce repetitive code changes.
What Is gopls?
gopls is the official Go language server. It connects Go development tools with code editors through the Language Server Protocol (LSP).
Instead of implementing Go-specific functionality separately in every editor, gopls provides language intelligence through a common interface.
It supports features such as:
- Code completion and suggestions.
- Go to definition and references.
- Diagnostics and error reporting.
- Rename operations.
- Code formatting.
- Import organization.
- Code actions and refactoring.
- Test-related editor features.
- Workspace symbol navigation.
For example, when a developer opens a Go file in Visual Studio Code, the Go extension communicates with gopls to provide language-aware functionality.
The editor displays the available actions, while gopls understands Go syntax, types, packages, and references.
This separation makes it possible to improve Go development features without implementing every feature independently in each editor.
Why Interactive Refactoring Matters
Traditional refactoring actions generally work with the information available at the cursor position or selected code.
For example, when extracting a variable, gopls can examine the selected expression and generate a declaration automatically.
However, consider a struct that needs several serialization tags:
type UserProfile struct {
ID int64
FirstName string
LastName string
EmailAddr string
}
A developer may want JSON and database tags, but the correct naming convention depends on the application.
One project may use camelCase for JSON fields, while another uses snake_case. Database columns may follow a different naming convention altogether.
A traditional automatic refactoring operation has two choices: apply a predefined default or avoid offering the operation.
Interactive refactoring provides another option. The language server can ask the developer which tags and naming convention to use before generating the changes.
This makes refactoring more flexible without requiring developers to leave their editor.
Understanding Interactive Code Actions
A code action is an operation associated with a particular section of source code.
In Visual Studio Code, code actions are commonly available through the lightbulb icon, the Quick Fix menu, or the Refactor menu.
When a developer selects an action, the editor communicates with gopls to request and apply the required changes.
Interactive code actions extend this process by allowing gopls to request additional information before applying the transformation.
The workflow looks like this:
- The developer selects code or places the cursor on a relevant declaration.
- The editor requests available code actions from gopls.
- The developer selects an interactive refactoring operation.
- gopls asks for the required information through an editor dialog.
- The developer enters values or selects an available option.
- gopls validates the input and calculates the transformation.
- The editor applies the resulting changes to the workspace.
Unlike a simple text replacement, the language server can use the additional information to make changes across declarations, methods, imports, and references.
How LSP Fits Into the Process
The Language Server Protocol allows editors and language servers to communicate through structured requests and responses.
Most traditional code actions are parameterless from the user's perspective. The server calculates the changes using the current source selection.
Interactive refactoring introduces a mechanism through which the language server can collect user input before completing the operation.
The Go team developed this capability in collaboration with the Dart team and proposed it as an extension to the broader LSP ecosystem.
It is important to understand that interactive dialogs are not yet a standard LSP capability supported by every language server and editor. The implementation described here is provided by gopls, with client support in the official Go extension for Visual Studio Code.
Setting Up Interactive Refactoring in Visual Studio Code
To use the new functionality, you need a compatible gopls version and an editor extension that supports interactive code actions.
Install or Update gopls
You can install the required gopls version using the Go toolchain:
go install golang.org/x/tools/[email protected]
Make sure the Go binary directory is included in your system PATH.
Check the installed version:
gopls version
The command should report gopls v0.24.0.
Update the Go Extension
Open Visual Studio Code and install or update the official Go extension.
The interactive refactoring implementation described by the Go team is supported by the official Go extension v0.56.0.
After updating the extension, reload Visual Studio Code if necessary.
Open a Go Workspace
Open a Go project that contains a valid go.mod file.
For example:
mkdir gopls-refactoring-demo
cd gopls-refactoring-demo
go mod init example.com/gopls-refactoring-demo
Create a Go source file and start working with it in Visual Studio Code.
Once gopls is running, its code actions should become available when the cursor is placed on supported declarations or expressions.
The exact menu items depend on the selected code and the refactoring operation.
Adding Struct Tags Interactively
Adding struct tags is one of the most useful examples of interactive refactoring.
Go structs are commonly used to represent API request models, database records, configuration objects, and application data.
Different packages use struct tags to control how fields are interpreted.
For example:
type UserProfile struct {
ID int64
FirstName string
LastName string
EmailAddr string
}
Suppose the application uses JSON serialization and database mapping. You want to add both json and db tags.
Instead of writing every tag manually, you can use the interactive Add struct tags action.
Steps to Add Struct Tags
- Open the Go file containing the struct.
- Place the cursor inside the struct definition.
- Open the Refactor menu or code actions menu.
- Select Add struct tags.
- Enter the required tags, such as json,db.
- Choose the desired naming convention.
- Review and apply the generated changes.
The first dialog allows you to choose the tags. The next dialog allows you to select a naming convention.
Supported conventions include camelCase, snake_case, lisp-case, PascalCase, and Title Case.
The resulting struct may look like this:
type UserProfile struct {
ID int64 `json:"id" db:"id"`
FirstName string `json:"first_name" db:"first_name"`
LastName string `json:"last_name" db:"last_name"`
EmailAddr string `json:"email_addr" db:"email_addr"`
}
The generated tags follow the selected naming convention.
This is particularly useful when working with large data models that contain many fields.
Removing Selected Struct Tags
Interactive refactoring also supports removing struct tags.
Consider a struct that contains both JSON and database tags:
type Product struct {
ID int64 `json:"id" db:"product_id"`
Name string `json:"name" db:"product_name"`
Price float64 `json:"price" db:"product_price"`
}
Suppose the application no longer uses the database mapping tags but still needs JSON serialization.
Instead of removing every tag manually, select Remove struct tags and specify db as the tag to remove.
The resulting struct preserves the JSON tags:
type Product struct {
ID int64 `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
}
This is safer than removing all tags and recreating the ones the application still needs.
Implementing Interfaces With Interactive Refactoring
Interfaces are an important part of Go application design.
They allow developers to define behavior independently of concrete implementations.
Consider an application that defines a storage interface:
type Storage interface {
Save(data []byte) error
Load(id string) ([]byte, error)
}
Now suppose you have a concrete type:
type FileStorage struct {
Directory string
}
You want FileStorage to implement Storage.
Normally, you would write the required methods manually. Interactive refactoring can generate the method declarations for you.
Using the Implement Interface Action
- Place the cursor on the FileStorage type declaration.
- Open the Refactor or code actions menu.
- Select the action for adding methods to implement an interface.
- Enter the interface name.
- Choose the matching interface from the suggestions.
- Review the generated methods.
gopls can search for interface types in the workspace and standard library and provide matching suggestions.
For example, after selecting the Storage interface, it can generate:
func (f *FileStorage) Save(data []byte) error {
panic("unimplemented")
}
func (f *FileStorage) Load(id string) ([]byte, error) {
panic("unimplemented")
}
The generated methods use the receiver type and the interface method signatures.
The placeholder implementations still need to be completed by the developer. Interactive refactoring generates the structure, not the business logic.
Working With Generic Interfaces
The feature also supports interfaces that use type parameters.
For example:
type Repository[T any] interface {
Save(item T) error
Find(id string) (T, error)
}
When implementing a generic interface, gopls may ask for concrete type arguments.
For example, if the concrete type stores User values, you can select User as the type argument.
The generated methods can then use the appropriate instantiated signatures:
type UserRepository struct{}
func (r *UserRepository) Save(item User) error {
panic("unimplemented")
}
func (r *UserRepository) Find(id string) (User, error) {
panic("unimplemented")
}
This saves time when implementing interfaces with several methods or generic parameters.
Moving Declarations Between Files and Packages
Another important refactoring task is moving declarations.
As Go applications grow, developers often split large files into smaller files to improve organization.
For example, a package may contain unrelated types, helper functions, and business logic in a single file.
Moving a declaration manually requires more than cutting and pasting code. Developers may also need to move dependent declarations, update imports, and fix references across the workspace.
The interactive Move declaration operation is designed to simplify this process.
Understanding the Move Declaration Workflow
The proposed workflow allows developers to:
- Place the cursor on a top-level declaration.
- Select Move declaration.
- Choose an existing destination Go file or enter a new file path.
- Review the proposed changes.
- Apply the transformation.
The refactoring can move dependent declarations, such as methods and unexported helpers that are required by the selected type.
It can also update references across the workspace and organize imports in the affected files.
Consider the following package:
package from
import (
"fmt"
"strings"
)
const bar = "bar"
type Foo struct{}
func (f Foo) Print() {
fmt.Println(bar)
}
func Baz() string {
return strings.ToUpper("baz")
}
If Foo is moved to another package, its method and the private constant it depends on may need to move with it.
The resulting destination package can contain:
package to
import "fmt"
const bar = "bar"
type Foo struct{}
func (f Foo) Print() {
fmt.Println(bar)
}
The original package can retain unrelated declarations such as Baz.
This kind of transformation is more involved than a normal file move because package boundaries and symbol visibility must be considered.
The Go team's October 2026 announcement describes this operation as a preview and notes that it was being prepared for an upcoming gopls release. Check the installed gopls release before expecting it to be available in a particular environment.
Other Refactoring Features Available in gopls
Interactive refactoring is part of a larger set of code transformation capabilities.
gopls already supports several useful refactoring operations.
| Refactoring | Purpose |
|---|
| Extract variable | Moves an expression into a new local variable |
| Extract constant | Creates a constant from a selected expression |
| Extract function | Moves selected statements into a new function |
| Extract method | Moves selected statements into a method |
| Extract to new file | Moves declarations into another file |
| Inline variable | Replaces a variable reference with its initializer |
| Inline call | Replaces a function or method call with its body where supported |
| Invert if | Negates an if condition and swaps the branches |
| Change quote | Converts between raw and interpreted string literals |
| Split lines | Places elements of a list on separate lines |
| Join lines | Combines supported multiline expressions |
| Implement interface | Generates method declarations for an interface |
Most of these actions can be applied directly when gopls has enough information.
Interactive refactoring extends this collection by allowing the developer to supply additional details when the transformation needs them.
Using Code Actions Outside Visual Studio Code
Although Visual Studio Code provides the main interactive workflow described here, gopls is not limited to one editor.
Other editors can use gopls through LSP.
For example, Emacs users working with Eglot can invoke available code actions through:
M-x eglot-code-actions
However, the ability to display interactive dialogs depends on whether the editor client supports the interactive protocol extension.
A traditional code action may work even when interactive forms are not supported.
gopls also provides command-line support for inspecting and applying certain code actions.
For example:
gopls codeaction -kind=source.organizeImports -exec -write main.go:#0
This command applies import organization to the specified file.
The CLI is useful for automating supported transformations, reviewing changes, and working with scripts. It should not be treated as a replacement for the interactive editor workflow when an operation requires user input through a dialog.
What Happens When a Refactoring Input Is Invalid?
Interactive refactoring does not simply accept every value entered by the developer.
The language server can validate the supplied information before applying changes.
For example, when selecting an interface to implement, the selected name must resolve to a valid interface type.
If the input is invalid, gopls can return information about the validation error and request corrected input.
This is useful because it prevents an incomplete or invalid selection from immediately modifying the source code.
The editor can display the validation result and allow the developer to correct the value.
The exact presentation depends on the editor's support for interactive code actions.
Best Practices for Using gopls Refactoring
Interactive refactoring can save time, but generated changes should still be reviewed like any other source-code modification.
The following practices help make refactoring safer:
- Keep gopls and the Go editor extension updated to compatible versions.
- Use the correct Go workspace and module configuration.
- Review generated struct tags before committing changes.
- Check interface method signatures and complete placeholder implementations.
- Review import changes when moving declarations.
- Run gofmt after manual changes.
- Run go test ./... after significant refactoring.
- Review changes across package boundaries carefully.
- Use version control so that large transformations can be inspected or reverted.
- Avoid applying broad refactorings to generated source files.
For larger projects, make structural changes in small steps. This makes it easier to identify the cause of a compilation or test failure.
Common Issues and Troubleshooting
Refactoring Actions Are Not Visible
The available actions depend on the cursor position and selected code.
For example, the Add struct tags action requires the cursor to be inside a struct definition. The Implement interface action is offered when the cursor is on a suitable package-level type declaration.
Check that the selected code is supported by the operation.
Interactive Dialogs Do Not Appear
Interactive refactoring requires compatible editor and language-server support.
Verify that gopls and the Go extension are updated to the required versions. An editor that supports ordinary LSP code actions may not necessarily support interactive forms.
gopls Does Not Find an Interface
The interface must be available in the current workspace or in an accessible dependency.
Check that the relevant package is included in the workspace and that the Go module dependencies are resolved.
Also verify that the selected type is a valid target for the implementation operation.
Moving a Declaration Changes Package References
Moving a declaration across packages can affect visibility and imports.
Exported identifiers can be accessed from other packages, but unexported identifiers cannot. Review references and package dependencies after the transformation.
Generated Code Does Not Offer Refactoring Actions
gopls does not generally offer transformation actions for files identified as generated through the conventional DO NOT EDIT comment.
If a file is generated, update the source or generator rather than relying on manual refactoring of the generated output.
Advantages and Limitations of Interactive Refactoring
Interactive refactoring makes several Go development tasks easier.
It reduces repetitive typing, helps generate consistent struct tags, simplifies interface implementation, and provides a structured way to collect information before modifying code.
It also improves the separation between the language server and editor. Instead of building separate dialog logic for every refactoring in every editor, the language server can describe the information it needs.
However, there are limitations.
Interactive code actions require compatible client support. The proposed dialog capability is not yet part of the standard LSP feature set supported by every editor. Some advanced operations may also be available only as previews or in specific gopls versions.
Generated method bodies still require implementation, and moving declarations between packages requires careful review of dependencies and visibility.
Interactive refactoring is therefore an assistant for code transformations, not a replacement for developer review.
Summary
gopls is becoming more capable of handling complex Go refactoring tasks directly inside the editor.
Interactive refactoring allows the language server to ask developers for additional information before applying changes. This makes operations such as adding struct tags, removing selected tags, and implementing interfaces more flexible.
The capability is available in gopls v0.24.0 and the official Go extension for Visual Studio Code v0.56.0. More advanced operations, including moving declarations across files and packages, are also being developed.
For Go developers, this means less time spent on repetitive code changes and more time focused on application logic. As interactive code actions become more widely supported, they can make Go development tools more useful across different editors and development environments.
Join the conversation! Your thoughts help the community grow.