0
0
GoHow-ToBeginner · 3 min read

How to Implement Graph in Go: Simple Guide with Example

To implement a graph in Go, use a map where keys are nodes and values are slices of connected nodes, representing an adjacency list. This structure allows easy addition of edges and traversal. Use map[string][]string for a simple graph with string nodes.
📐

Syntax

A graph can be represented using an adjacency list in Go with a map where each key is a node and the value is a slice of nodes it connects to.

Example parts:

  • map[string][]string: map with string keys and slice of strings as values.
  • Keys represent nodes.
  • Values represent edges to connected nodes.
go
graph := make(map[string][]string)
graph["A"] = []string{"B", "C"}
graph["B"] = []string{"A", "D"}
graph["C"] = []string{"A"}
graph["D"] = []string{"B"}
💻

Example

This example shows how to create a simple undirected graph using adjacency lists and print its connections.

go
package main

import "fmt"

func main() {
	// Create an empty graph
	graph := make(map[string][]string)

	// Add edges (undirected)
	addEdge := func(u, v string) {
		graph[u] = append(graph[u], v)
		graph[v] = append(graph[v], u)
	}

	addEdge("A", "B")
	addEdge("A", "C")
	addEdge("B", "D")

	// Print graph
	for node, edges := range graph {
		fmt.Printf("%s: %v\n", node, edges)
	}
}
Output
A: [B C] B: [A D] C: [A] D: [B]
⚠️

Common Pitfalls

Common mistakes when implementing graphs in Go include:

  • Not initializing the map before adding edges, causing runtime errors.
  • Forgetting to add edges in both directions for undirected graphs.
  • Using slices without appending properly, which can overwrite existing edges.
go
package main

import "fmt"

func main() {
	// Wrong: map not initialized
	var graph map[string][]string
	// graph["A"] = append(graph["A"], "B") // This will panic

	// Correct initialization
	graph = make(map[string][]string)
	graph["A"] = append(graph["A"], "B")

	fmt.Println(graph)
}
Output
map[A:[B]]
📊

Quick Reference

Tips for implementing graphs in Go:

  • Use map[node][]node for adjacency lists.
  • Initialize maps with make before use.
  • For undirected graphs, add edges in both directions.
  • Use slices and append to add edges safely.

Key Takeaways

Use a map with slices to represent adjacency lists for graphs in Go.
Always initialize your map with make before adding edges.
Add edges in both directions for undirected graphs.
Use append to add nodes to slices without overwriting existing edges.
Print and verify your graph structure to avoid common mistakes.