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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分