Go语言之如何给*int32类型赋值

直接上代码:

  1.  
    package main
  2.  
     
  3.  
    import "fmt"
  4.  
     
  5.  
    func main() {
  6.  
    var num *int32
  7.  
    var i int32 = 5
  8.  
    // 针对*int32的,先创建一个i类型,然后取i的地址,赋值给*int32
  9.  
    num = &i
  10.  
    fmt.Println("=====>:\t", num)
  11.  
    fmt.Println("=====>:\t", *num)
  12.  
    }

运行结果:

  1.  
    =====>: 0xc042064080
  2.  
    =====>: 5
  3.  
     
  4.  
    Process finished with exit code 0

下面的形式是不可以的:

  1.  
    package main
  2.  
     
  3.  
    import "fmt"
  4.  
     
  5.  
    func main() {
  6.  
    var num *int32
  7.  
    *num = 5
  8.  
    fmt.Println("=====>:\t", num)
  9.  
    fmt.Println("=====>:\t", *num)
  10.  
    }

运行结果:

  1.  
    panic: runtime error: invalid memory address or nil pointer dereference
  2.  
    [signal 0xc0000005 code=0x1 addr=0x0 pc=0x48b4ea]
  3.  
     
  4.  
    goroutine 1 [running]:
  5.  
    main.main()
  6.  
    E:/Program/go2/goPath/src/xingej-go/xingej-go/xingej-go666/string/test.go:7 +0x2a
  7.  
     
  8.  
    Process finished with exit code 2

原因?
  可能是取不到常量5的地址

转载于:https://blog.51cto.com/xingej/2117313

posted @ 2020-05-25 21:24  twoheads  阅读(114)  评论(0编辑  收藏