声明一个包含有5个整数指针类型的数组,我们可以在初始化时给相应位置的元素默认值。下面是给索引为0的元素一个新建的的int类型指针(默认为0),给索引为1的元素指向值v的地址,剩下的没有指定默认值的元素为指针的zero值也就是nil

package main

import "fmt"

func main() {


    var v int = 6
    array := [5]*int{0: new(int), 1: &v}
    fmt.Println(len(array))
    fmt.Println(*array[0])
    fmt.Println(*array[1])
    v2 := 7
    array[2] = &v2
    fmt.Println("------------------")
    for i, v := range array {
        fmt.Printf("index %d, address %v value is ", i, v)
        if v != nil {
            fmt.Print(*v)
        } else {
            fmt.Print("nil")
        }
        fmt.Println("  ")
    }
}
5
0
6
------------------
index 0, address 0x115a6150 value is 0  
index 1, address 0x115a60ec value is 6  
index 2, address 0x115a6184 value is 7  
index 3, address <nil> value is nil  
index 4, address <nil> value is nil  

Process finished with exit code 0