📌  相关文章
📜  go pointers - Go 编程语言 - Go 编程语言(1)

📅  最后修改于: 2023-12-03 14:41:32.270000             🧑  作者: Mango

Go Pointers

Introduction

In Go programming language, pointers are variables that store the address of another variable. Go pointer provides a way to access and manipulate a memory address, which enables the data to be shared between functions and to be changed directly.

Pointer Declaration

To declare a pointer in Go, we use the * operator followed by the data type of the variable pointed to. For example, to declare a pointer to an integer:

var ptr *int

Here, ptr is a pointer to an integer variable.

Pointer Initialization

A pointer can be initialized by setting it to nil or to the address of a variable. To initialize a pointer to nil:

var ptr *int = nil

To initialize a pointer to the address of a variable:

var x int = 10
var ptr *int = &x

Here, ptr will point to the memory address of x.

Dereferencing Pointers

To get the value stored in the memory location pointed to by a pointer, we use the * operator. This is known as dereferencing a pointer. For example:

var x int = 10
var ptr *int = &x

fmt.Println(*ptr)

This will print the value of x, which is 10.

Passing Pointers to Functions

In Go, we can pass pointers as arguments to functions. This allows us to share memory between functions and to modify the value of the variable directly. For example:

func increment(ptr *int) {
    *ptr++
}

func main() {
    var x int = 10
    var ptr *int = &x

    increment(ptr)

    fmt.Println(x)
}

This will print the value of x, which is 11 after being incremented by the increment function using the ptr pointer.

Conclusion

Go pointers provide a way to access and manipulate memory addresses directly. By using pointers, we can share memory between functions and modify variables directly. Understanding pointers is an important concept in Go programming language.