donglu1472 2016-10-25 01:19
浏览 26
已采纳

我怎样才能初始化像这样的指针切片?

I was surprised I could initialize a slice 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 was expecting to have to write something more verbose like:

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

Where would I find this in the documentation?

  • 写回答

1条回答 默认 最新

  • doujiang2812 2016-10-25 01:39
    关注

    From 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.

    Basically, it already knows each element will be a *index, so it saves you having to actually type &index over and over again.

    If the slice type is not the same as the element type (perhaps it is a slice of an interface type), you would have to specify the type of each element like so:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳