dominikbraun / graph

A library for creating generic graph data structures and modifying, analyzing, and visualizing them.
https://graph.dominikbraun.io
Apache License 2.0
1.82k stars 96 forks source link

altering an edge property #94

Closed Zincr0 closed 1 year ago

Zincr0 commented 1 year ago

Given an already created edge (1 to 2), changing the weight doesn't seems to be currently possible

Tested

anEdge, _ := g.Edge(1, 2)
anEdge.Properties.Weight = 5
anEdge.Properties = graph.EdgeProperties{Weight: 11}`
_ = g.AddEdge(1, 2, graph.EdgeWeight(50))`

none changes the weight.

A function to do this or a workaround in documentation would be great. Very nice library btw.

dominikbraun commented 1 year ago

Thanks for your question! You're right: At the moment, edges are immutable. This is mainly because I haven't figured out an appropriate API design yet, but it's definitely a planned feature and it will be a concern in one of the next few releases.

One backward-compatible workaround would be to remove the edge and re-create it with the new weight. In fact, I did this myself and created a small helper function:

func updateEdgeWeight(g graph.Graph[int, int], source, target, value int) {
    _ = g.RemoveEdge(source, target)
    _ = g.AddEdge(source, target, graph.EdgeWeight(value))
}

Using this function, your example could be solved as follows:

updateEdgeWeight(g, 1, 2, 50)

I hope I'll be able to provide a more convenient solution soon!

dominikbraun commented 1 year ago

Graph.UpdateEdge will be part of the upcoming release next Monday.

dominikbraun commented 1 year ago

graph v0.20 introduces support for updating edge properties.