How is it that I can initialize such a pointer?

I was surprised to be able to initialize a fragment of pointers in this way:

package main

import (
    "fmt"
)

type index struct {
    i, j int
}

func main() {
    indices := []*index{{0, 1}, {1, 3}} // Why does this work?

    fmt.Println(*indices[1])
}

I expected that I should write something more detailed, for example:

indices := []*index{&index{0, 1}, &index{1, 3}}

Where can I find this in the documentation?

+4
source share
1 answer

From spec :

In a composite literal of an array, fragment, or type of map T, elements or Keys of a map that are themselves composite literals, can correspond to the type of the literal if it is identical to the type of element or key T. Similarly, elements or keys that are addresses of composite literals can evade & T when the item or key type is * T.

, , *index, , &index .

(, ), :

indices := []interface{}{&index{0, 1}, &index{1, 3}}

+5

Source: https://habr.com/ru/post/1658752/


All Articles