Solution 3: Go Generics
Let’s solve the challenge set in the previous lesson.
We'll cover the following...
Solution
Here is the updated structures.go
code with the delete()
and search()
functionality.
Press + to interact
package mainimport ("fmt")type node[T any] struct {Data Tnext *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 = &nreturn}if l.start.next == nil {l.start.next = &nreturn}temp := l.startl.start = l.start.nextl.add(data)l.start = temp}func (l *list[T]) search(data T, equal func(T, T) bool) bool {current := l.startfor 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.nextreturn}current := l.startvar prev *node[T] = nilfor current != nil {if equal(current.Data, data) {prev.next = current.nextreturn}prev = currentcurrent = 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 elementscurrent := myList.startfor current != nil {fmt.Println("*", current.Data)current = current.next}// Search for an elementequalFunc := 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 elementmyList.delete(9, equalFunc)fmt.Println("After deleting 9:")current = myList.startfor 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 ...