Home  >  Article  >  Backend Development  >  How to Convert a Slice of Anonymous Structs to a Slice of Non-Anonymous Structs in Go?

How to Convert a Slice of Anonymous Structs to a Slice of Non-Anonymous Structs in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 11:40:01864browse

How to Convert a Slice of Anonymous Structs to a Slice of Non-Anonymous Structs in Go?

Type Conversion Between Slices of Structs in Go

Problem:

In an attempt to convert a slice of anonymous structs to a slice of non-anonymous structs, errors occur. This raises questions about the equivalence of structs with and without JSON tags and the compatibility of different slices.

Answer:

Differences Between Struct Types:

Structs with different JSON tags are considered different types because the tags affect the encoding and decoding of JSON data.

Conversion Options:

1. Copy Through Iteration:

This is the recommended method, but it is slower and more verbose. It involves copying each element of the anonymous struct slice into the non-anonymous struct slice.

<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>

2. Unsafe Conversion:

This is an unsafe method that assumes the underlying data structure of both struct types is identical.

<code class="go">return *(*ListSociete)(unsafe.Pointer(&res)), nil</code>

Warning:

The unsafe conversion may result in unpredictable behavior and is not recommended for general use. Using it may lead to memory corruptions or other unexpected errors.

The above is the detailed content of How to Convert a Slice of Anonymous Structs to a Slice of Non-Anonymous Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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