go - 我怎么能像这样初始化一片指针呢?

标签 go

我很惊讶我可以用这种方式初始化一片指针:

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

我原以为必须写一些更冗长的东西,比如:

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

我可以在文档的什么地方找到它?

最佳答案

来自 the spec :

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.

基本上,它已经知道每个元素都是一个 *index,因此您不必一遍又一遍地实际键入 &index

如果 slice 类型与元素类型不同(可能是接口(interface)类型的 slice ),您必须像这样指定每个元素的类型:

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

关于go - 我怎么能像这样初始化一片指针呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229931/

相关文章:

go - 无法使用 Docker 容器自动运行简单的 Go Web 服务器(func (*Template) Execute)

go - 在 Golang 中推回 vector 导致程序崩溃

json - 无法让 Json 在 ag Grid 中显示只是说正在加载

go - 如何编写mbox格式的文件?

go - 为什么在 Ubuntu 上无限执行例程后不会从线程打印

Go chi 渲染难以处理绑定(bind)列表

struct - 在 Go 中初始化结构

go - 声明递归/多维映射

go - 从 Sarama 的错误 channel 中读取的正确方法是什么?

go - 在本地使用带有 go mod 的子包