MENU

Go 学习笔记:指针

August 23, 2021 • Read: 168 • Golang

与C语言相同,go也是提供了指针支持的

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 11:58:03
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    var p *int
    var n int = 12
    p = &n
    fmt.Printf("%x\n%x\n", p, &n)
    fmt.Printf("%d\n%d\n", *p, n)
}

如果不对指针赋值,那么他的值就会使nil,使用%x输出出来就是0

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 14:20:58
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    var p *int
    fmt.Printf("%x\n", p)
    fmt.Println(p)
}

当然,你也可以将C语言的数组指针挪用到go里来

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 14:41:38
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    var array = [3]int{1, 3, 6}
    var p *[3]int = &array // 数组指针

    for _, i := range *p {
        fmt.Println(i)
    }

}

指针数组也是同理

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 14:51:00
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    var array = [3]int{1, 3, 6}
    var p [3]*int // 指针数组

    for idx, _ := range array {
        p[idx] = &array[idx]
    }

    for _, item := range p {
        fmt.Println(*item)
    }
}

还有指向指针的指针

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 14:54:38
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

func main() {
    var value int = 12
    var p *int = &value
    var pp **int = &p

    fmt.Println(value)
    fmt.Println(p, *p, &p)
    fmt.Println(pp, *pp, **pp)
}
Archives Tip
QR Code for this page
Tipping QR Code