Search⌘ K

Solution 3: Go Generics

Understand how to implement and use Go generics by working through linked list operations like delete and search. Learn how to handle generic data comparisons with custom equality functions to build flexible and reusable code structures.

We'll cover the following...

Solution

Here is the updated structures.go code with the delete() and search() functionality.

Go (1.19.0)
package main
import (
"fmt"
)
type node[T any] struct {
Data T
next *node[T]
}
type list[T any] struct {
start *node[T]
}
func (l *list[T]) add(data T) {
n := node[T]{
Data: data,
next: nil,
}
if l.start == nil {
l.start = &n
return
}
if l.start.next == nil {
l.start.next = &n
return
}
temp := l.start
l.start = l.start.next
l.add(data)
l.start = temp
}
func (l *list[T]) search(data T, equal func(T, T) bool) bool {
current := l.start
for current != nil {
if equal(current.Data, data) {
return true
}
current = current.next
}
return false
}
func (l *list[T]) delete(data T, equal func(T, T) bool) {
if l.start == nil {
return
}
if equal(l.start.Data, data) {
l.start = l.start.next
return
}
current := l.start
var prev *node[T] = nil
for current != nil {
if equal(current.Data, data) {
prev.next = current.next
return
}
prev = current
current = current.next
}
}
func main() {
var myList list[int]
fmt.Println(myList)
myList.add(12)
myList.add(9)
myList.add(3)
myList.add(9)
// Print all elements
current := myList.start
for current != nil {
fmt.Println("*", current.Data)
current = current.next
}
// Search for an element
equalFunc := func(a, b int) bool { return a == b }
fmt.Println("Search for 3:", myList.search(3, equalFunc))
fmt.Println("Search for 7:", myList.search(7, equalFunc))
// Delete an element
myList.delete(9, equalFunc)
fmt.Println("After deleting 9:")
current = myList.start
for current != nil {
fmt.Println("*", current.Data)
current = current.next
}
}

Code explanation

Let’s look at the explanation of the delete() function. This function removes a specific ...