How to Convert a Slice of Anonymous Structs to a Slice of Defined Structs in Golang?

Susan Sarandon
Release: 2024-10-26 16:33:30
Original
435 people have browsed it

How to Convert a Slice of Anonymous Structs to a Slice of Defined Structs in Golang?

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(&amp;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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!