How to Safely Convert Between Slices of Structs in Go: A Guide to Type Conversion and Best Practices

Linda Hamilton
Release: 2024-10-31 10:50:02
Original
264 people have browsed it

How to Safely Convert Between Slices of Structs in Go: A Guide to Type Conversion and Best Practices

Type Conversion between Slices of Structs in Go

When working with slices of structs in Go, it is important to understand the differences between various types. In this case, we have the following types:

  • ListSociete: A custom struct type used for storing a list of Societe structs.
  • []Societe: A slice of Societe structs.
  • []struct{Name string json:"a.name"}: An anonymous struct type with a single field Name and a JSON tag.

Question 1: Are []struct{Name string} and []struct{Name string json:"a.name" } different?

Yes, they are different because of the JSON tag json:"a.name". The Go specifications clearly state that two struct types are identical only if they have the same fields, names, types, and tags.

Question 2: Is ListSociete different from []struct{Name string}?

Yes, they are different because ListSociete is a custom type while []struct{Name string} is an anonymous type. They also have different field names.

_Solution:

There are two options for converting between these types:

Option 1: Copy through Iteration

This method is safe and reliable, but requires explicit copying:

<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

This unsafe method directly converts the underlying data structure:

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

This method should be used with caution as it may cause unexpected behavior.

_Playground Example: http://play.golang.org/p/lfk7qBp2Gb

The above is the detailed content of How to Safely Convert Between Slices of Structs in Go: A Guide to Type Conversion and Best Practices. 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!