How to Initialize a Slice of Pointers to Structs in Go: A Breakdown of Anonymous Struct Syntax?

Patricia Arquette
Release: 2024-11-01 13:15:06
Original
524 people have browsed it

How to Initialize a Slice of Pointers to Structs in Go: A Breakdown of Anonymous Struct Syntax?

Initializing Slice of Pointers: Understanding Anonymous Struct Syntax

In Chapter 7 of GOPL, an example is given for initializing a slice of pointers to Track structs:

var tracks = []*Track{
    {"Go", "Delilah", "From the Roots Up", 2012, length("3m38s")},
    {"Go", "Moby", "Moby", 1992, length("3m37s")},
    {"Go Ahead", "Alicia Keys", "As I Am", 2007, length("4m36s")},
    {"Ready 2 Go", "Martin Solveig", "Smash", 2011, length("4m24s")},
}
Copy after login

To understand the syntax, let's examine the following code where we define a custom Ex struct and initialize its slices:

type Ex struct {
    A, B int
}

a := []Ex{Ex{1, 2}, Ex{3, 4}}
b := []Ex{{1, 2}, {3, 4}}
c := []*Ex{&Ex{1, 2}, &Ex{3, 4}}
d := []*Ex{{1, 2}, {3, 4}}
e := []*Ex{{1, 2}, &Ex{3, 4}}
Copy after login

In cases a and b, we initialize the slices with instances of the Ex struct using a shortcut syntax:

f := []<type>{{...}, {...}}
Copy after login

This is equivalent to:

f := []<type>{<type>{...}, <type>{...}}
Copy after login

For cases c, d, and e, the syntax requires a bit more explanation. The initialization:

f := []*<type>{{...}, {...}}
Copy after login

Is analogous to:

f := []*<type>{&<type>{...}, &<type>{...}}
Copy after login

In other words, the curly braces following the type specify the values for a struct of that type, and the ampersands create pointers to those structs.

Finally, in the following code, we receive a syntax error:

f := []*Ex{&{1, 2}, &{3, 4}} // Syntax Error!
Copy after login

This is because the curly braces must be followed by the name of a type, not an anonymous struct. The correct syntax would be:

f := []*Ex{&Ex{1, 2}, &Ex{3, 4}}
Copy after login

The above is the detailed content of How to Initialize a Slice of Pointers to Structs in Go: A Breakdown of Anonymous Struct Syntax?. 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!