英文:
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论