Home > Backend Development > Golang > How to use golang pointers

How to use golang pointers

(*-*)浩
Release: 2019-12-31 13:41:08
Original
2490 people have browsed it

How to use golang pointers

#The basic meaning of a pointer is the memory address where certain values ​​are stored.                                                                                                                                                     (Recommended to learn: go)

In Golang, although not all values ​​can be taken out of address (although they are also stored in memory, such as const), all Variables must be able to take out addresses.

Variables are values ​​stored in a memory area [1]. Not only is x in the familiar var x int a variable, a more complex expression can also represent a variable, such as sliceA[0], mapB["key"], and structC.FieldD. That is, they can each have their own pointers.

When we need to modify the variable content of the structure, the structure variable parameters passed in by the method need to use pointers, which are the addresses of the structures, and the variables of the architecture in the map need to be modified. Sometimes you also need to use the structure address as the value of the map.

Go can directly create a new struct pointer

In golang, we can get a structure through ptr := &A{Value: 1} A pointer to the value of body A; but in C it cannot be obtained through a separate assignment statement:

typedef struct {    
int value;
} 
A;A *ptr1; // 无法给 ptr 所指的值赋值
A *ptr2 = &A{1}; // 没有这样的语法
A a = {1}; // 再通过 &a 可以得到指针
Copy after login

If this difference is just a grammatical appearance, the other difference may be related to bugs.

2. Pointers to local variables can be safely returned in Go

In the above C code example, we can indeed declare some variables, but if these declarations are Completed within a method, such as:

A *init(){
    A *ptr;
    return ptr;}
Copy after login

or

A *init(){
    A a;
    return &a;}
Copy after login

Then, this declared local variable is an automatic variable (automatic variable[3]), and the original method is also It's the init() method. After it ends, these automatic variables "disappear".

The above is the detailed content of How to use golang pointers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template