
Go 允许在初始化指针切片时省略显式的 & 符号和类型名,编译器会自动将复合字面量(如 {0, 1})识别为对应结构体并取其地址,前提是切片元素类型为 *T 且字面量类型恰好匹配 T。
go 允许在初始化指针切片时省略显式的 `&` 符号和类型名,编译器会自动将复合字面量(如 `{0, 1}`)识别为对应结构体并取其地址,前提是切片元素类型为 `*t` 且字面量类型恰好匹配 `t`。
这是 Go 语言规范中定义的复合字面量类型推导规则,位于 Go Language Specification → 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 ofT. Similarly, elements or keys that are addresses of composite literals may elide the&Twhen the element or key type is*T.
简言之:当声明一个 []*T 类型的切片时,若每个元素使用 T{...} 形式的字面量,Go 编译器会自动补全为 &T{...} —— 这是语法糖,而非运行时行为,完全由编译器静态推导完成。
✅ 正确示例(自动补 &):
type index struct { i, j int }
indices := []*index{{0, 1}, {1, 3}} // 等价于 []*index{&index{0,1}, &index{1,3}}
fmt.Println(*indices[0]) // {0 1}⚠️ 注意事项:
该简化*仅适用于 `[]T
、[N]T或map[K]T等明确指向T` 的类型**;-
若目标类型是接口(如
[]interface{}),则无法自动推导,必须显式取址并确保类型兼容:// ❌ 编译错误:cannot use {0,1} (type index) as type interface{} in slice literal // bad := []interface{}{{0, 1}, {1, 3}} // ✅ 正确:需显式构造指针并转换(若满足接口契约) good := []interface{}{&index{0, 1}, &index{1, 3}} 结构体字段顺序与可导出性仍需满足常规要求(如字段名首字母大写、无未导出字段冲突等);
此语法不适用于嵌套指针(如
[]**T),此时仍需完整书写&(&T{...})。
? 小结:这一特性显著提升了初始化指针集合的简洁性与可读性,是 Go “少即是多”设计哲学的典型体现。掌握它不仅能写出更地道的 Go 代码,也能帮助你更深入理解类型系统与字面量解析机制。建议在团队代码规范中明确接纳该写法,并在 Code Review 中将其视为推荐实践。

















