How do I write a generic graph structure in Go?

In Go, you can create a generic graph structure using maps and slices. A graph can represent various types of data relationships through its nodes and edges. Below is an example of how to implement a simple generic graph structure in Go.

package main import "fmt" // Graph represents a generic graph structure type Graph[T any] struct { vertices map[T]bool edges map[T]map[T]bool } // NewGraph creates a new graph func NewGraph[T any]() *Graph[T] { return &Graph[T]{ vertices: make(map[T]bool), edges: make(map[T]map[T]bool), } } // AddVertex adds a vertex to the graph func (g *Graph[T]) AddVertex(vertex T) { if !g.vertices[vertex] { g.vertices[vertex] = true g.edges[vertex] = make(map[T]bool) } } // AddEdge adds an edge between two vertices in the graph func (g *Graph[T]) AddEdge(v1, v2 T) { if g.vertices[v1] && g.vertices[v2] { g.edges[v1][v2] = true g.edges[v2][v1] = true // For undirected graph } } // Display prints the graph func (g *Graph[T]) Display() { for vertex := range g.vertices { fmt.Print(vertex, ": ") for neighbor := range g.edges[vertex] { fmt.Print(neighbor, " ") } fmt.Println() } } func main() { graph := NewGraph[int]() graph.AddVertex(1) graph.AddVertex(2) graph.AddVertex(3) graph.AddEdge(1, 2) graph.AddEdge(2, 3) graph.Display() }

generic graph structure Go generics graph implementation in Go data structures in Go