Golang 转移指针到指针(双指针)
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
极客教程