krahets/hello-algo · error

error

Error message

error

What it means

`addEdge(vet1, vet2)` in the English `graphAdjList` panics with "error" when an endpoint is absent from the adjacency map or the two endpoints are the same. The undirected model requires both vertices pre-registered and disallows self-loops.

Source

Thrown at en/codes/go/chapter_graph/graph_adjacency_list.go:45

	for _, edge := range edges {
		g.addVertex(edge[0])
		g.addVertex(edge[1])
		g.addEdge(edge[0], edge[1])
	}
	return g
}

/* Get the number of vertices */
func (g *graphAdjList) size() int {
	return len(g.adjList)
}

/* Add edge */
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
	_, ok1 := g.adjList[vet1]
	_, ok2 := g.adjList[vet2]
	if !ok1 || !ok2 || vet1 == vet2 {
		panic("error")
	}
	// Add edge vet1 - vet2, add anonymous struct{},
	g.adjList[vet1] = append(g.adjList[vet1], vet2)
	g.adjList[vet2] = append(g.adjList[vet2], vet1)
}

/* Remove edge */
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
	_, ok1 := g.adjList[vet1]
	_, ok2 := g.adjList[vet2]
	if !ok1 || !ok2 || vet1 == vet2 {
		panic("error")
	}
	// Remove edge vet1 - vet2
	g.adjList[vet1] = DeleteSliceElms(g.adjList[vet1], vet2)
	g.adjList[vet2] = DeleteSliceElms(g.adjList[vet2], vet1)
}

View on GitHub (pinned to 69932aed18)

Solutions

  1. Add both vertices with `addVertex` first.
  2. Drop self-loops from input (`vet1 != vet2`).
  3. Assert existence via a `hasVertex` helper.
  4. Recover when ingesting untrusted edge data.

Example fix

// before
g.addEdge(a, b) // panic if missing endpoint or a == b

// after
if hasVertex(g, a) && hasVertex(g, b) && a != b {
    g.addEdge(a, b)
}
Defensive patterns

Strategy: validation

Validate before calling

if !hasVertex(g, vet1) || !hasVertex(g, vet2) || vet1 == vet2 {
    return errors.New("endpoints missing or self-loop")
}
g.addEdge(vet1, vet2)

Type guard

func hasVertex(g *graphAdjList, v Vertex) bool {
    _, ok := g.adjList[v]
    return ok
}

Try / catch

defer func() {
    if r := recover(); r != nil {
        // skip the bad edge during bulk ingestion
    }
}()
g.addEdge(vet1, vet2)

Prevention

When it happens

Trigger: `addEdge` on a vertex not added via `addVertex`; `addEdge(v, v)`; constructing an edge before its vertices.

Common situations: Edge lists loaded without the vertex set, self-loop entries in data, or a typo making one endpoint unknown.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/6e79b433974b1fdc. Report an issue: GitHub.