Home  >  Article  >  Backend Development  >  How to Initialize a Slice of Pointers to Structs in Go: A Breakdown of Anonymous Struct Syntax?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 13:15:06525browse

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")},
}

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

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

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

This is equivalent to:

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

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

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

Is analogous to:

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

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!

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

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!

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