Home > Article > Backend Development > How to Resolve Duplicate Field Issues When Embedding Same-Named Structs?
Overcoming Duplicate Field Issues When Embedding Two Same-Named Structs
Embedding multiple types with the same name within a single struct can result in a duplicate field issue. This is evident when trying to embed both an SQL store and a file store within a datastore struct, leading to a redundant "Store" field.
Alternative Approach: Type Alias
To resolve this conflict, consider using a type alias. This involves creating a new name for the embedded type, effectively creating an alternate spelling for the original type.
For instance, in the provided example, you could define a type alias called "SqlStore" to represent the SQL store:
<code class="go">type SqlStore = sql.Store</code>
Once the alias is established, the datastore struct can embed "SqlStore" along with the fileStore:
<code class="go">type datastore struct { *SqlStore *file.Store }</code>
By utilizing a type alias, the conflicting field names are avoided, as the alias creates a distinct spelling for the embedded SQL store type, resolving the duplicate field issue.
The above is the detailed content of How to Resolve Duplicate Field Issues When Embedding Same-Named Structs?. For more information, please follow other related articles on the PHP Chinese website!