0

The code below defines a directed graph using petgraph

extern crate petgraph;

use petgraph::graph::DiGraph;

fn main() {
    // Define the list of edges. Each edge is in the format (source, target, edge weight).
    let edge_list = vec![(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)];

    // Declare the directed graph using the `from_edges` function.
    let graph = DiGraph::<i32, i32>::from_edges(&edge_list);

    // Display the edges and nodes of the graph.
    for edge in graph.raw_edges() {
        println!(
            "Edge from {:?} to {:?} with weight {:?}",
            edge.source(),
            edge.target(),
            edge.weight
        );
    }
}

The code above works correctly. However, when I add type annotation to the edge_list as shown in the code below, I get an error.

enter image description here

extern crate petgraph;

use petgraph::graph::DiGraph;

fn main() {
    // Define the list of edges. Each edge is in the format (source, target, edge weight).
    let edge_list: Vec<(i32, i32)> = vec![(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)];

    // Declare the directed graph using the `from_edges` function.
    let graph = DiGraph::<i32, i32>::from_edges(&edge_list);

    // Display the edges and nodes of the graph.
    for edge in graph.raw_edges() {
        println!(
            "Edge from {:?} to {:?} with weight {:?}",
            edge.source(),
            edge.target(),
            edge.weight
        );
    }
}
the trait bound `NodeIndex: From<i32>` is not satisfied
the trait `From<Ix>` is implemented for `NodeIndex<Ix>`
required because of the requirements on the impl of `Into<NodeIndex>` for `i32`

Please explain the cause of this error and provide any relevant documentation or resources.

TKS0113
  • 1
  • 1
  • A `usize` is not a `i32`, in the first example the type of `edge_list` is inferred to be `Vec<(usize, usize)>` – cafce25 Apr 02 '23 at 08:48
  • The code after adding the type annotation was incorrect and has been corrected. The modified code still produces the following error. ``` the trait bound `NodeIndex: From` is not satisfied the trait `From` is implemented for `NodeIndex` required because of the requirements on the impl of `Into` for `usize` ``` – TKS0113 Apr 02 '23 at 08:54
  • Ah yea my bad replace all `usize` with `u32` in my previous statement. – cafce25 Apr 02 '23 at 09:08
  • The question was not clear and has been corrected. I get an error when I add a type that is displayed on VSCode as a type annotation. – TKS0113 Apr 02 '23 at 09:35
  • Well the type VSCode infers is simply wrong, Rust [infers `(u32, u32)` for the items](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=701daee9c75cf5b355ea6e97055f0a79) – cafce25 Apr 02 '23 at 09:41
  • I changed to the following type inference and it worked. edge_list: Vec<(u32, u32)> Thanks! – TKS0113 Apr 02 '23 at 10:02

0 Answers0