Home >Backend Development >Golang >What is the life cycle of Go language variables?

What is the life cycle of Go language variables?

青灯夜游
青灯夜游Original
2023-01-10 17:05:152180browse

In the Go language, the life cycle of a variable refers to the time interval during which the variable effectively exists during the running of the program. The life cycle of global variables is consistent with the running cycle of the entire program; the life cycle of local variables is dynamic, starting from the declaration statement that creates the variable until the variable is no longer referenced.

What is the life cycle of Go language variables?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

The life cycle of Go language variables

The life cycle of a variable refers to the time interval during which the variable effectively exists during the running of the program. .

The life cycle of a variable is inseparably linked to the scope of the variable:

  • Global variables: Its life cycle and the running cycle of the entire program are Consistent;

  • Local variable: Its life cycle is dynamic, starting from the declaration statement that creates the variable until the variable is no longer referenced;

  • Formal parameters and function return values: They are all local variables, created when the function is called, and destroyed after the function call is completed.

for t := 0.0; t < cycles*2*math.Pi; t += res {
    x := math.Sin(t)
    y := math.Sin(t*freq + phase)
    img.SetColorIndex(
        size+int(x*size+0.5), size+int(y*size+0.5),
        blackIndex, // 最后插入的逗号不会导致编译错误,这是Go编译器的一个特性
    )               // 小括号另起一行缩进,和大括号的风格保存一致
}

In the above code, the temporary variable t is created at the beginning of each loop, and then the temporary variables x and y are created in each loop iteration. Temporary variables x and y are stored in the stack. As the function execution ends (execution encounters the last }), its memory is released.

The difference between stack and heap is:

  • Heap: Heap is used to store memory segments that are dynamically allocated during process execution. . Its size is not fixed and can be dynamically expanded or reduced. When a process calls functions such as malloc to allocate memory, the newly allocated memory is dynamically added to the heap (the heap is expanded). When free and other functions are used to release memory, the released memory is removed from the heap (the heap is reduced);

  • Stack (stack): The stack is also called a stack and is used to store programs. The temporarily created local variables are the local variables defined in the curly braces { } of our function.

During the compilation phase of the program, the compiler will automatically choose to allocate storage space for local variables on the stack or heap according to the actual situation, regardless of whether the variable is declared using the var or new keywords. Influence compiler choice.

var global *int
func f() {
    var x int
    x = 1
    global = &x
}
func g() {
    y := new(int)
    *y = 1
}

In the above code, the variable x in function f must be allocated on the heap, because it can still be found through the package-level global variable after the function exits, although it is defined inside the function. In Go language terms, this local variable x escapes from function f.

On the contrary, when function g returns, the variable *y is no longer used, which means it can be recycled immediately. Therefore, *y does not escape from function g. The compiler can choose to allocate *y's storage space on the stack, or it can choose to allocate it on the heap, and then the GC (garbage collection mechanism) of the Go language will reclaim the memory of this variable. space.

In actual development, there is no need to deliberately implement variable escape behavior, because escaped variables require additional memory allocation, and the optimization of performance may have a subtle impact.

Although the Go language can help us allocate and release memory, in order to develop high-performance applications we still need to understand the declaration cycle of variables. For example, if you assign a local variable to a global variable, it will prevent the GC from recycling the local variable, causing unnecessary memory usage and thus affecting the performance of the program.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What is the life cycle of Go language variables?. 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