krahets/hello-algo · error
error
Error message
error
What it means
`addEdge(vet1, vet2)` in the undirected `graphAdjList` panics with "error" when an endpoint is not present in the adjacency map, or when the two endpoints are identical. The book's model forbids self-loops and requires both vertices to already exist, so `!ok1 || !ok2 || vet1 == vet2` is treated as a programming error.
Source
Thrown at 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
}
/* 获取顶点数量 */
func (g *graphAdjList) size() int {
return len(g.adjList)
}
/* 添加边 */
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 添加边 vet1 - vet2, 添加匿名 struct{},
g.adjList[vet1] = append(g.adjList[vet1], vet2)
g.adjList[vet2] = append(g.adjList[vet2], vet1)
}
/* 删除边 */
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 删除边 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
- Register both endpoints with `addVertex` before `addEdge`.
- Filter self-loops out of input before inserting (`vet1 != vet2`).
- Add a `hasVertex` helper and assert both endpoints exist first.
- Recover around bulk edge insertion when data is untrusted.
Example fix
// before
g.addEdge(a, b) // panic if a or b missing, 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 offending edge and continue ingesting the rest
}
}()
g.addEdge(vet1, vet2) Prevention
- Always addVertex for both endpoints before addEdge.
- Sanitize imported edge lists: drop self-loops and unknown vertices.
- Wrap bulk ingestion in recover so one bad record doesn't abort the batch.
When it happens
Trigger: Calling `addEdge` for a vertex never added via `addVertex`; calling `addEdge(v, v)`; building an edge before its vertices are registered.
Common situations: Loading an edge list whose endpoints were not pre-loaded, JSON/CSV input containing self-loops, or a typo so both endpoints compare unequal but one is unknown.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/2a185237234038e2.
Report an issue: GitHub.