Golang指向指针的指针(双指针)介绍

先决条件:Go中的指针
【Golang指向指针的指针(双指针)介绍】Go编程语言中的指针或高朗是一个变量, 用于存储另一个变量的内存地址。指针是一个特殊的变量, 因此它甚至可以指向任何类型的变量。基本上, 这看起来像是一个指针链。当我们定义一个指向指针的指针时, 第一个指针用于存储第二个指针的地址。这个概念有时被称为双指针.
如何在Golang中声明指向指针的指针?
声明Pointer to Pointer类似于声明
Go中的指针
。不同之处在于我们必须另外放置一个"
*
’, 指针名称前的名称。通常, 当我们使用
var关键字
以及类型。下面的示例和图像将以更好的方式解释该概念。
范例1:在下面的程序中指针pt2存储的地址pt1指针。取消引用pt2即* pt2将给出变量的地址v或者你也可以说指针的值pt1。如果你会尝试** pt2那么这将给出变量的值v即100。

Golang指向指针的指针(双指针)介绍

文章图片
// Go program to illustrate the // concept of the Pointer to Pointer package mainimport "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 = & pt1fmt.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 =100Address of variable V is =0x414020The Value of pt1 is =0x414020Address of pt1 is =0x40c128The value of pt2 is =0x40c128Value at the address of pt2 is or *pt2 =0x414020*(Value at the address of pt2 is) or **pt2 =100

范例2:让我们在上述程序中进行一些更改。通过使用取消引用更改指针的值来为指针分配一些新值, 如下所示:
Golang指向指针的指针(双指针)介绍

文章图片
// Go program to illustrate the // concept of the Pointer to Pointer package mainimport "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 = & pt1fmt.Println( "The Value of Variable v is = " , v)// changing the value of v by assigning // the new value to the pointer pt1 *pt1 = 200fmt.Println( "Value stored in v after changing pt1 = " , v)// changing the value of v by assigning // the new value to the pointer pt2 **pt2 = 300fmt.Println( "Value stored in v after changing pt2 = " , v) }

输出如下:
The Value of Variable v is =100Value stored in v after changing pt1 =200Value stored in v after changing pt2 =300

    推荐阅读