Type Conversion between Slices of Structs in Golang
This inquiry centers around type conversion between slices of structs. Specifically, we aim to convert a slice of anonymous structs to a slice of a defined struct.
Underlying Issue
The issue arises due to the difference between the two struct types:
- Societe struct with a single field named Name
- Anonymous struct with a single field named Name tagged with json:"a.name"
The presence of the tag creates a distinct struct type, preventing direct conversion.
Solution Options
Option 1: Iteration and Copying
- Iterate through both slices and manually copy each field from the anonymous struct to the Societe struct.
- This approach is safe and reliable but less efficient due to the iterative nature.
<code class="go">ls := make(ListSociete, len(res))
for i := 0; i < len(res); i++ {
ls[i].Name = res[i].Name
}
return ls, nil</code>
Copy after login
Option 2: Unsafe Conversion
- Direct type conversion using unsafe pointers.
- This method bypasses type checking and may result in runtime errors if the underlying data structures change unexpectedly.
-
Caution: Use this approach cautiously as it compromises type safety.
<code class="go">return *(*ListSociete)(unsafe.Pointer(&res)), nil</code>
Copy after login
Best Practices
- Define appropriate structs to represent the data model.
- Use explicit type conversions where necessary to maintain type safety.
- Opt for the safe iteration and copying approach for reliable conversions.
The above is the detailed content of How to Convert a Slice of Anonymous Structs to a Slice of Defined Structs in Golang?. For more information, please follow other related articles on the PHP Chinese website!