2

When we declare a slice of structs, but set the data type to a pointer to the struct, does go automatically convert the literals to pointers?

type book struct {
    id int
    name string
}

var books = []*book {
    {1, "Yellow moon"}, // ---> Is this a pointer to book OR just book
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Shubhang b
  • 597
  • 1
  • 5
  • 12
  • 1
    It's a pointer to book, of course, because you can't store anything else than that in a slice of pointer to book. – Peter Dec 28 '19 at 10:37

3 Answers3

2

It will be a pointer to book, same as &book{1, "Yellow moon"}, but the spec allows to elide the type and the & operator, because it's obvious from the type.

var books = []*book {
    {1, "Yellow moon"},  // This is the same as &book{1, "Yellow moon"}
}

Spec: Composite literals:

Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T. Similarly, elements or keys that are addresses of composite literals may elide the &T when the element or key type is *T.

[][]Point{{{0, 1}, {1, 2}}}  // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}

[2]*Point{{1.5, -3.5}, {}}   // same as [2]*Point{&Point{1.5, -3.5}, &Point{}}
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
2

It is possible to define with and without type:

https://play.golang.org/p/CB2MDPDztrc

Donutloop
  • 427
  • 3
  • 15
0

Does go auto convert composite literals inside a slice to pointers if I declare the slice as a pointer to a struct?

it is default behavior of pointer to struct

To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

https://tour.golang.org/moretypes/4

Peter
  • 29,454
  • 5
  • 48
  • 60
Artiko
  • 69
  • 1
  • 3
  • 8