What are the stack and heap in go language?

青灯夜游
Release: 2023-01-04 09:11:45
Original
4116 people have browsed it

The stack is a data structure, which is the memory space reserved for the execution thread; the stack only allows data to be put into one end of the linear table, and then the data is taken out at this end, that is, according to the first-in-last-out, last-in-first-out Remove the elements from the stack in the order they are removed. The heap is a data structure that is a memory space reserved for dynamic allocation; unlike the stack, there is no fixed pattern for allocating and reallocating blocks from the heap; you can allocate and release it at any time.

What are the stack and heap in go language?

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

Stack and heap in Go language

There are two very important concepts in programming languages, heap and stack,

Heap and stack are two very important data Structure is often used when editing programs, and Go language is no exception.

Let’s take a look at these two data structures.

Stack

The stack only allows data to be put into one end of the linear table, and then the data is taken out at this end, that is, according to the first-in, last-out, Remove elements from the stack in last-in-first-out order.

The process of putting elements into the stack is called pushing. Pushing onto the stack will increase the number of elements on the stack. The last element put into the stack is at the top of the stack, and the first element put into the stack is at the bottom of the stack.

When taking an element out of the stack, it can only be taken out from the top of the stack. After taking out the element, the number of the stack will become smaller. The element put in first will always be taken out last, and the element put in last will always be taken out. First to be taken out.

What are the stack and heap in go language?

We often use arrays to simulate the use of a stack:

The implementation code of pushing and popping the stack is as follows:

package main
import (
   "fmt"
   "errors"
)

//使用数组来模拟一个栈的使用
type Stack struct {

   MaxTop int       // 表示我们栈最大可以存放数个数
   Top int          // 表示栈顶, 因为栈顶固定,因此我们直接使用Top
   arr [5]int       // 用一个数组模拟栈
}

//入栈函数
func (this *Stack) Push(val int) (err error) {

   //先判断栈是否满了
   if this.Top == this.MaxTop - 1 {
      fmt.Println("stack full")
      return errors.New("stack full")
   }
   this.Top++
   //放入数据
   this.arr[this.Top] = val
   return
}

//出栈函数
func (this *Stack) Pop() (val int, err error) {
   //判断栈是否空
   if this.Top == -1 {
      fmt.Println("stack empty!")
      return 0, errors.New("stack empty")
   }

   //先取值,再 this.Top--
   val =  this.arr[this.Top]
   this.Top--
   return val, nil
}

//遍历栈,注意需要从栈顶开始遍历
func (this *Stack) List() {
   //先判断栈是否为空
   if this.Top == -1 {
      fmt.Println("stack empty")
      return
   }
   fmt.Println("栈的情况如下:")
   for i := this.Top; i >= 0; i-- {
      fmt.Printf("arr[%d]=%d\n", i, this.arr[i])
   }
}

func main() {

   stack := &Stack{
      MaxTop : 5,    // 表示最多存放5个数到栈中
      Top : -1,      // 当栈顶为-1,表示栈为空
   }

   //入栈
   stack.Push(1)
   stack.Push(2)
   stack.Push(3)
   stack.Push(4)
   stack.Push(5)
   stack.List()//显示

   //出栈
   val, _ := stack.Pop()
   fmt.Println("出栈val=", val)    // 5
   stack.List()                    //显示
}
Copy after login

Heap

The heap in memory allocation is similar to placing various furniture in a room. The size of the furniture can be large or small. When allocating memory, you need to find a piece of furniture. Place the furniture in a space that is large enough to accommodate the furniture.

After repeatedly placing and vacating furniture, the space in the room will become messy. At this time, if you place furniture in this space, you will find that although there is enough space, each space is distributed in different areas. , there is no continuous space to place furniture. At this time, the memory allocator needs to adjust and optimize these spaces.

What are the stack and heap in go language?

Compared with heap allocated memory and stack allocated memory, the heap is suitable for memory allocation of unpredictable sizes.

Allocation of heap and stack

After the variable definition is completed, it is generally allocated on the heap and stack space, in which space does it exist? It depends on whether there is dynamic allocation of memory (new/malloc).

For example, the following case

Case one

var p *int    //全局指针变量
func f(){
    var i int
    i = 1
    p = &i    //全局指针变量指向局部变量i
}
Copy after login

Case two

func f(){
    p := new(int) //局部指针变量,使用new申请的空间
    *p = 1
}
Copy after login

In the first case, var is used to define local variables, but due to i assignment Given the global pointer variable p, when the function ends, i will not be released at this time, so the local variable i is applied on the heap (manually released by the programmer).

  • Local variable: A variable defined in a function. It has a dynamic life cycle: a new entity is created every time it is executed and survives until no one uses it (for example, there is no external pointer Point to it, there is no path to access this variable when the function exits) At this time, the space it occupies will be recycled

In the second case, use new to apply for space, because p will be lost after exiting the function will be released, so p is applied on the stack (automatically released)

[Related recommendations: Go video tutorial, Programming teaching]

The above is the detailed content of What are the stack and heap in go language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
go
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