Skip to content

Commit

Permalink
docs: Clarify when graph methods return None? (petgraph#491)
Browse files Browse the repository at this point in the history
This is a docs change, and should not affect any functionality.

While looking about the API, I didn't quite understand why I had to `unwrap()` every time I wanted to access an edge or a node. I understand now it's because that weight or node might not exist, but that was only clear to me after looking at the source code.

This change adds a line to the relevant docstrings that explain when a `Some()` will be returned vs when a `None` will be returned.

The docstring for `remove_node` already had a similar line in it:
```
/// Remove `a` from the graph if it exists, and return its weight.
/// If it doesn't exist in the graph, return `None`.
```
So I made sure the lines I added were phrased similarly to keep the code base consistent, like 
```
/// If ____ doesn't exist in the graph, return `None`.
```
  • Loading branch information
beyarkay authored and teuron committed Oct 9, 2022
1 parent 82f8c29 commit dd22b3b
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/graph_impl/mod.rs
Expand Up @@ -534,13 +534,15 @@ where

/// Access the weight for node `a`.
///
/// If node `a` doesn't exist in the graph, return `None`.
/// Also available with indexing syntax: `&graph[a]`.
pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
self.nodes.get(a.index()).map(|n| &n.weight)
}

/// Access the weight for node `a`, mutably.
///
/// If node `a` doesn't exist in the graph, return `None`.
/// Also available with indexing syntax: `&mut graph[a]`.
pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
Expand Down Expand Up @@ -606,19 +608,23 @@ where

/// Access the weight for edge `e`.
///
/// If edge `e` doesn't exist in the graph, return `None`.
/// Also available with indexing syntax: `&graph[e]`.
pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
self.edges.get(e.index()).map(|ed| &ed.weight)
}

/// Access the weight for edge `e`, mutably.
///
/// If edge `e` doesn't exist in the graph, return `None`.
/// Also available with indexing syntax: `&mut graph[e]`.
pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
}

/// Access the source and target nodes for `e`.
///
/// If edge `e` doesn't exist in the graph, return `None`.
pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
self.edges
.get(e.index())
Expand Down

0 comments on commit dd22b3b

Please sign in to comment.