Nev*_*evs 1 arrays pointers go
p是一个指向数组的指针arr,我们可以arr通过 using获取数组*p,但是为什么不能通过 using 获取第二个元素*p[2]?
它会导致错误:
p[1] 的无效间接(int 类型)
以下代码:
arr := [4]int{1,2,3,4}
var p *[4]int = &arr
fmt.Println(p) // output &[1 2 3 4]
fmt.Println(*p) // output [1 2 3 4]
fmt.Println(p[1]) // output 2
fmt.Println(*p[1]) //generate an error:invalid indirect of p[1] (type int)
Run Code Online (Sandbox Code Playgroud)
因为*p[1]意味着*(p[1])。并且(p[1])是int不能取消引用的。
先用括号解引用指针,然后索引结果:
fmt.Println((*p)[1])
Run Code Online (Sandbox Code Playgroud)
另请注意,p[1]没有括号和取消引用是允许的并且有效,因为p它是指向数组的指针,并且引用了Spec: Index 表达式:
a[x]是简写(*a)[x]
但请注意,指向切片类型的指针是不允许的。