我可以帮你翻译。这是你要翻译的内容: 我如何初始化一个指针切片呢?

huangapple go评论113阅读模式
英文:

How is it that I can initialize a slice of pointers like this?

问题

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

package main

import (
	"fmt"
)

type index struct {
	i, j int
}

func main() {
	indices := []*index{{0, 1}, {1, 3}} // 为什么这样可以工作?

	fmt.Println(*indices[1])
}

我原本以为我需要写得更冗长一些,像是:

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

我在文档中可以找到这个内容吗?

英文:

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

得分: 5

规范中可以看到:

> 在类型为T的数组、切片或映射的复合字面值中,如果元素或映射键本身是复合字面值,并且其类型与T的元素或键类型相同,则可以省略相应的字面值类型。类似地,如果元素或键是复合字面值的地址,并且元素或键类型是*T,则可以省略&T。

基本上,它已经知道每个元素将是*index,所以它省去了你重复输入&index的麻烦。

如果切片类型与元素类型不同(例如它是接口类型的切片),你需要像这样指定每个元素的类型:

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

英文:

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

huangapple
  • 本文由 发表于 2016年10月25日 09:19:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/40229931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定