Ver en Español
Data Structures in Go: Stacks
Apr 16, 2023
Updated: Jun 25, 2026

Data Structures in Go: Stacks

Data structures are an organized collection of data used to store, retrieve and manipulate information efficiently. These structures include linked lists, stacks, queues, trees, arrays, graphs and hash tables. Each data structure has its own characteristics and uses, which lets programmers choose the right structure for each situation. These structures can also be combined to build more complex programming solutions.

Stacks (Stack)

A stack, or Stack, is a data structure based on the idea of LIFO (Last In, First Out). This means the element that was added most recently is the first one to be removed. This structure is commonly used to store and manipulate data in an orderly, efficient way. For example, stacks can be used to undo operations, store function calls and keep data in a specific order.

Some characteristics of a stack are:

  • It is a LIFO (Last In, First Out) data structure.
  • It only allows access to one element: the top element.
  • Only two main operations can be performed: push (add an element) and pop (remove an element).

A Stack is designed to be an efficient data structure. Stacks are commonly used to implement recursion and to store data in a specific order.

Main methods we should implement

When we implement a stack, these are the main methods:

  • Push: add an element to the stack.
  • Pop: remove the top element.
  • Peek (also known as top): get the top element without removing it.
  • Empty (also known as isEmpty): check whether the stack is empty or not.
  • Size: get the size of the stack.

Picture a stack of 4 elements, where the top element (A) is the first one to be removed.

Here's an example of a stack written in Go. Remember that the Spanish word for stack is pila:

package main

import (
	"fmt"
)

// Libro is a struct to store book information
type Libro struct {
	Título  string
	Autor   string
	Páginas int
}

// StackLibros is a data structure that allows inserting and removing books
// using the LIFO (Last In First Out) principle.
type StackLibros struct {
	data []Libro
}

// Push adds a book to the stack
func (s *StackLibros) Push(value Libro) {
	s.data = append(s.data, value)
}

// Pop removes the top element of the stack
func (s *StackLibros) Pop() Libro {
	if len(s.data) == 0 {
		return Libro{}
	}

	value := s.data[len(s.data)-1]
	s.data = s.data[:len(s.data)-1]
	return value
}

// Peek gets the top element of the stack without removing it
func (s *StackLibros) Peek() Libro {
	if len(s.data) == 0 {
		return Libro{}
	}
	return s.data[len(s.data)-1]
}

// Empty checks whether the stack is empty or not
func (s *StackLibros) Empty() bool {
	return len(s.data) == 0
}

// Size gets the size of the stack
func (s *StackLibros) Size() int {
	return len(s.data)
}

func main() {
	s := StackLibros{}
	s.Push(Libro{"Cien años de soledad", "Gabriel García Márquez", 417})
	s.Push(Libro{"El principito", "Antoine de Saint-Exupéry", 77})
	s.Push(Libro{"El alquimista", "Paulo Coelho", 163})

	fmt.Println("Tamaño del stack:", s.Size())
	fmt.Println("Elemento superior:", s.Peek().Título)

	for !s.Empty() {
		libro := s.Pop()
		fmt.Printf("Título: %s, Autor: %s, Páginas: %d\n", libro.Título, libro.Autor, libro.Páginas)
	}
}

This code compiles and runs fine on current versions of Go: the slice backed stack pattern (append to insert and s.data[:len(s.data)-1] to remove) is timeless and doesn't rely on any API that will become deprecated.

Why is a Stack the foundation of other, more complex data structures?

A stack is a very simple data structure that can serve as the foundation for building more complex structures such as trees, graphs and queues. This is because a stack offers an efficient way to store and manipulate data. Stacks are also commonly used to implement recursion, which makes them a useful tool for creating more complex data structures.

A little bit of history

The Stack dates back to the early days of computing, when programmers were looking for the best way to store and manipulate data efficiently. The LIFO (Last In, First Out) principle is commonly attributed to Alan Turing (around 1946) and, independently, to Friedrich L. Bauer and Klaus Samelson, who patented the principle in the late 1950s. The idea was to create an efficient data structure in which the last element added is the first one removed. Over time, the stack has become a basic tool for building more complex data structures such as trees, graphs and queues. It's commonly used to implement recursion and to store data in a specific order. Today, the stack remains one of the most widely used data structures in software engineering.

Conclusions

In conclusion, the Stack is a very useful and widely used data structure for storing and organizing information. It offers an easy way to save and retrieve data efficiently. This structure is essential for programming, since it lets programmers implement a wide variety of solutions. The Stack is also an indispensable tool for implementing recursive algorithms.

Exercises to practice

Below is an exercise so you can practice the "Stack" structure in Go and send your solution as a Pull request to this repository: Go Para Principiantes.

Exercise: Create a Stack structure in Go to store animal names and add the elements 'Perro', 'Gato', 'Conejo' and 'Loro' to the stack.

Summary

  • Stacks are data structures based on the idea of LIFO (Last In, First Out) and are widely used in programming.
  • Stacks let you perform push (add an element) and pop (remove an element) operations, plus other functions like peek (get the top element without removing it), empty (check whether the stack is empty) and size (get the size of the stack).
  • Stacks are essential when implementing recursive algorithms and serve as a foundation for more complex data structures such as trees, graphs and queues.

Now that you know the basics of stacks and how to implement them in Go, you can explore how to apply them to different problems and situations in your programming projects. I hope this post is useful to you and that you can apply it to a project you have in mind. Leave me a comment if it helped, and remember that if you liked it you can also share it using the social links below. Good luck and happy coding!

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorias