Home >Backend Development >Golang >The difference between golang pointers and references

The difference between golang pointers and references

下次还敢
下次还敢Original
2024-04-21 00:52:05778browse

Both pointers and references are used to access variables indirectly: the pointer points to the variable address and directly accesses the variable. References are aliases that store pointers to variables and access variables indirectly. Pointers are defined and dereferenced with *, and modifying the pointer affects the variable. To reference, use & to get the address, * to reference the address, and modifying the reference does not affect the variable. Pointers can point to any variable, including pointers; references can only point to variables.

The difference between golang pointers and references

Golang pointers and references

The difference between pointers and references

Pointers and references are mechanisms used to indirectly access variables in Golang. The main difference is:

  • A pointer is a variable that holds the address of another variable. It points directly to the variable.
  • A reference is an alias that stores a pointer to another variable. References do not point directly to variables.

Pointers

  • Use the * notation to define and dereference pointers.
  • The pointer points to the value of the variable, rather than directly containing the value.
  • Modifying the pointer will affect the pointed variable.
  • Pointers can point to variables of any type, including other pointers.

Reference

  • Use the & symbol to get the address of the variable, use the * symbol to reference it Get the address.
  • A reference always points to the address of a variable.
  • Modifying the reference will not affect the pointed variable.
  • References can only point to other variables, not pointers.

Example

<code class="go">package main

import "fmt"

func main() {
    // 创建一个变量
    x := 10

    // 创建一个指向 x 的指针
    p := &x

    // 创建一个引用 x 的引用
    q := &x

    // 通过指针修改变量
    *p = 20

    // 引用不会影响变量
    *q++

    // 打印结果
    fmt.Println("x:", x) // 输出: 20
}</code>

In this example:

  • p is a pointer to The pointer of x, modification of *p will update the value of x.
  • q is a reference to x, and modifications to *q will not update the value of x.

The above is the detailed content of The difference between golang pointers and references. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn