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

Patricia Arquette
Release: 2024-10-27 11:40:01
Original
961 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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