先决条件:Go 中的指针
Go 编程语言或 Golang 中的指针是一个变量,用于存储另一个变量的内存地址。指针是一种特殊的变量,因此它可以指向任何类型的变量,甚至可以指向指针。基本上,这看起来像一个指针链。当我们定义一个指向指针的指针时,第一个指针用于存储第二个指针的地址。这个概念有时被称为双指针。
如何在 Golang 中声明一个指向指针的指针?
声明指向指针的指针类似于在 Go 中声明指针。不同之处在于我们必须在指针名称之前放置一个额外的“*”。这通常在我们使用 var 关键字和类型声明指针变量时完成。下面的示例和图像将以更好的方式解释这个概念。
例 1:在下面的程序中,指针pt2存储了pt1指针的地址。取消引用pt2即*pt2将给出变量v的地址,或者您也可以说出指针pt1的值。如果你尝试**pt2那么这将给出变量v的值,即 100。
// Go program to illustrate the
// concept of the Pointer to Pointer
package main
import "fmt"
// Main Function
func main() {
// taking a variable
// of integer type
var V int = 100
// taking a pointer
// of integer type
var pt1 *int = &V
// taking pointer to
// pointer to pt1
// storing the address
// of pt1 into pt2
var pt2 **int = &pt1
fmt.Println("The Value of Variable V is = ", V)
fmt.Println("Address of variable V is = ", &V)
fmt.Println("The Value of pt1 is = ", pt1)
fmt.Println("Address of pt1 is = ", &pt1)
fmt.Println("The value of pt2 is = ", pt2)
// Dereferencing the
// pointer to pointer
fmt.Println("Value at the address of pt2 is or *pt2 = ", *pt2)
// double pointer will give the value of variable V
fmt.Println("*(Value at the address of pt2 is) or **pt2 = ", **pt2)
}
输出:
The Value of Variable V is = 100
Address of variable V is = 0x414020
The Value of pt1 is = 0x414020
Address of pt1 is = 0x40c128
The value of pt2 is = 0x40c128
Value at the address of pt2 is or *pt2 = 0x414020
*(Value at the address of pt2 is) or **pt2 = 100
示例 2:让我们对上述程序进行一些更改。通过使用取消引用更改指针的值来为指针分配一些新值,如下所示:
// Go program to illustrate the
// concept of the Pointer to Pointer
package main
import "fmt"
// Main Function
func main() {
// taking a variable
// of integer type
var v int = 100
// taking a pointer
// of integer type
var pt1 *int = &v
// taking pointer to
// pointer to pt1
// storing the address
// of pt1 into pt2
var pt2 **int = &pt1
fmt.Println("The Value of Variable v is = ", v)
// changing the value of v by assigning
// the new value to the pointer pt1
*pt1 = 200
fmt.Println("Value stored in v after changing pt1 = ", v)
// changing the value of v by assigning
// the new value to the pointer pt2
**pt2 = 300
fmt.Println("Value stored in v after changing pt2 = ", v)
}
输出:
The Value of Variable v is = 100
Value stored in v after changing pt1 = 200
Value stored in v after changing pt2 = 300