pointers - 结构指针的 slice 字面量的 golang 快捷语法

标签 pointers go literals

给定

type foo struct {
    id int
}

两者看起来是一样的

var foos = []*foo{
    {1},
    {2},
    {3}}

var foos = []*foo{
    &foo{1},
    &foo{2},
    &foo{3}}

这是为什么呢?虽然在 TGPL 中找不到它的提及。

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

最佳答案

可以跳过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.

关于pointers - 结构指针的 slice 字面量的 golang 快捷语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767698/

相关文章:

c++ - 在 C++ 中取消引用 NULL 指针

c - 为什么更改结构指针后会出现段错误?

c - 在没有stdio.h或math.h的情况下用C编写二进制文字?

c - CGO block 中的全局变量-GO中的内存泄漏和线程安全

c - 名字不会显示

go - 如何使用适用于 Windows 的 GitLab 管道进行构建

email - 如何在 Go 中发送带有附件的电子邮件

go - 当使用 k8s.io/client-go 库更改 kubernetes 部署时,获得通知的最佳方式是什么?

c# - 如何向文字对象添加方法和字段?

swift - Swift 中神秘的 float 转换错误