krahets/hello-algo · error
error
Error message
error
What it means
`addEdge(vet1, vet2)` in the Japanese `graphAdjList` panics with "error" when an endpoint is missing from the adjacency map or the two endpoints are identical. The undirected model forbids self-loops and requires both vertices to exist.
Source
Thrown at ja/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` first.
- Filter self-loops (`vet1 != vet2`).
- Assert existence via `hasVertex`.
- Recover when ingesting untrusted edges.
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 offending edge and continue ingestion
}
}()
g.addEdge(vet1, vet2) Prevention
- addVertex for both endpoints before addEdge.
- Sanitize imported data: drop self-loops and unknown vertices.
- Wrap bulk ingestion in recover.
When it happens
Trigger: `addEdge` on a vertex not added via `addVertex`; `addEdge(v, v)`; building an edge before registering vertices.
Common situations: Edge data loaded without the vertex set, self-loop entries, 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/caaab1c94ed63e01.
Report an issue: GitHub.