Fix case-insensitive field matching when both exported and unexported fields exist#230
Conversation
…rted fields exist
|
@jinzhu |
There was a problem hiding this comment.
Pull request overview
This PR updates the library’s case-insensitive struct field lookup so that when both exported and unexported fields differ only by case (a common protobuf pattern), the exported field is preferred during copying.
Changes:
- Reworked
fieldByNamecase-insensitive matching to prefer exact matches first, then prefer exported fields among case-insensitive matches. - Added tests intended to cover the exported-vs-unexported case-insensitive collision scenario.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
copier.go |
Alters case-insensitive field resolution to avoid selecting an unexported field when an exported field exists. |
copier_case_insensitive_test.go |
Adds regression tests around case-insensitive matching when both state and State exist. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This still does not fully resolve ambiguous case-insensitive matches such as State vs STate.
|
@jinzhu Commit |
🐛 Problem Description
When using case-insensitive field matching,
copiermay incorrectly match unexported fields when the target struct contains both exported (e.g.,State) and unexported fields (e.g.,state) with similar names, leading to copy failures or data loss.This issue is particularly common when working with protobuf-generated structs, as the protobuf compiler generates structs containing both public and private fields.
Reproduction Scenario
In case-insensitive mode,
copiermight match the privatestatefield instead of the publicStatefield, causing copy operations to fail.✅ Solution
Reimplemented the case-insensitive matching logic in the
fieldByNamefunction:Key Improvements
🧪 Test Coverage
Added comprehensive test cases:
📋 Changes
fieldByNamefunction incopier.gocopier_case_insensitive_test.gotest file🔄 Impact
This fix:
📚 Background
This fix addresses field matching ambiguity encountered in real-world projects using
copier, particularly in microservice architectures using protobuf. The solution ensures that when multiple fields match case-insensitively, the library intelligently selects the most appropriate field according to Go's visibility conventions.🧪 Testing
All tests pass, confirming the fix works correctly while maintaining backward compatibility.