Verified Production Fix
[golang/go] x/tools/gopls: modernizer for direct references to embedded fields in struct literals
GH-golang/go#77965 • Mar 07, 2026
### ROOT CAUSE
The issue arises because the modernizer in `gopls` does not correctly update direct references to embedded fields in struct literals to utilize the simplified syntax introduced in Go 1.27. This omission results in the tool failing to modernize code that could benefit from the new feature, potentially leading to compatibility issues or unnecessary verbosity.
### CODE FIX
To address this, we need to enhance the modernizer to identify struct literals where an embedded field is referenced with the outer struct's name and update them to use the simplified form.
1. **Modify the Modernizer**:
- **Step 1**: Locate all struct literals in the codebase.
- **Step 2**: For each struct literal, check if any field references use an embedded struct's name.
- **Step 3**: If an embedded field is referenced, remove the outer struct's name from the field reference.
**Example Code Update**:
Before:
b := B{A: A{X: 1}, Y: "hello"}
After:
b := B{A: {X: 1}, Y: "hello"}
**Implementation**:
- **File**: `x/tools/gopls/modernize/embedded_struct.go`
- **Add**: A function to parse struct literals and update embedded field references.
**Code**:
// modernizeEmbeddedStructs updates struct literals where embedded fields are referenced with the outer struct's name.
func modernizeEmbeddedStructs(f *File) {
// Iterate over all struct literals in the file.
for _, node := range f.Nodes {
if str, ok := node.(*ast.StructLit); ok {
// Check each field in the struct literal.
for i, field := range str.Fields {
if field.Type != nil && field.Type.IsStruct() {
// Remove the outer struct name if present.
if field.Tag == "struct:" {
// Simplify the field reference.
str.Fields[i] = &ast.Field{Value: field.Value}
}
}
}
}
}
}
This fix ensures that the modernizer correctly handles embedded field references in struct literals, making the codebase cleaner and compatible with Go 1.27's improvements.
Deploy with DigitalOcean
Use this fix in production instantly. Claim your $200 developer credit.
Get Started →
digital