```go
package main
import "fmt"
func main() {
var p *[]int
var arr []int = []int{1,2}
p=&arr
fmt.Println(p[0]) //报错:invalid operation: p[0] (index of type *[]int)
}
```
而下面的正确
```go
package main
import "fmt"
func main() {
var p *[2]int
var arr [2]int = [2]int{1,2}
p=&arr
fmt.Println(p[0]) //输出:1
}
```
为什么fmt.Println(p[0])报错啊,求指教!!!
<a href="/user/taatcc" title="@taatcc">@taatcc</a>
参见这个:http://docs.studygolang.com/ref/spec#Index_expressions
A primary expression of the form
a[x]
denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively.
......
For a of pointer to array type:
a[x] is shorthand for (*a)[x]
......
Otherwise a[x] is illegal.
索引表达式只支持这几种类型,其它的都是非法的。
你要对指向切片的指针使用索引表达式,就需要手动(*p)[0]
#3
更多评论