Golang List - CRUD Operations

1. Introduction

In Go, list management is an important aspect of handling ordered collections. While Go does not have a built-in list type as in some other languages, the container/list package provides a doubly linked list implementation that can be used to perform list operations. This post covers CRUD (Create, Read, Update, Delete) operations on lists in Go.

Definition

A doubly linked list provided by the container/list package allows for the efficient insertion and removal of elements. Each element holds a value and pointers to the next and previous elements in the list.

2. Program Steps

1. Create a new list.

2. Read (or iterate through) the list.

3. Update an element in the list.

4. Delete an element from the list.

3. Code Program

package main

import (
	"container/list"
	"fmt"
)

func main() {
	// Step 1: Create a new list and put some numbers in it
	l := list.New()
	e4 := l.PushBack(4)
	l.PushFront(1)
	e2 := l.InsertAfter(2, l.Front())

	// Step 2: Iterate through the list and print its contents
	fmt.Println("List contents:")
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value)
	}

	// Step 3: Update an element in the list (Change value 2 to 3)
	l.InsertBefore(3, e2)
	l.Remove(e2)

	// Step 4: Delete an element from the list (Remove the element with value 4)
	l.Remove(e4)

	// Print the list after update and delete operations
	fmt.Println("Updated list contents:")
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value)
	}
}

Output:

List contents:
1
2
4
Updated list contents:
1
3
4

Explanation:

1. package main and import "container/list" - The package declaration for the Go program and import statement for the doubly linked list package.

2. list.New() - Creates a new doubly linked list.

3. PushBack and PushFront - Add elements to the end and the beginning of the list, respectively.

4. InsertAfter and InsertBefore - Insert new elements after or before a specified element.

5. Iterating through the list is done using a for loop, starting from l.Front() and using e.Next() to move to the next element.

6. Remove - Deletes a specified element from the list.

7. e.Value - Accesses the value of the current list element in the iteration.

8. The output shows the contents of the list before and after the update and delete operations.


Comments