rustpetgraph

writing petgraph Dot to a file


I may be missing something very basic -- I am new to Rust. I'm attempting to write a petgraph::dot::Dot representation to a file.

The following small code example doesn't compile:

use petgraph::Graph;
use petgraph::dot::{Dot, Config};
use std::fs::File;
use std::io::Write;


fn main() {
    println!("hello graph!");
    let mut graph = Graph::<_, ()>::new();
    graph.add_node("A");
    graph.add_node("B");
    graph.add_node("C");
    graph.add_node("D");
    graph.extend_with_edges(&[
        (0, 1), (0, 2), (0, 3),
        (1, 2), (1, 3),
        (2, 3),
    ]);

    println!("{:?}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
    let mut f = File::create("example1.dot").unwrap();
    let output = format!("{}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
    f.write_all(&output.as_bytes());
}

Here's the compiler error output:

error[E0277]: `()` doesn't implement `std::fmt::Display`
  --> examples/graphviz.rs:21:32
   |
21 |     let output = format!("{}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `()` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `()`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required because of the requirements on the impl of `std::fmt::Display` for `petgraph::dot::Dot<'_, &petgraph::graph_impl::Graph<&str, ()>>`
   = note: required by `std::fmt::Display::fmt`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

The petgraph docs note that Dot implements Display trait and I based my code on sample code in trait.Display doc

I can get the code to work by changing the format string to {:?} but I thought that was only supposed to be for debugging. Is there a better way to write code to accomplish the same thing?


Solution

  • Dot implements Display only if both the edge and node weights implement Display.

    Since your edges are (), you cannot display this graph.

    For example, changing the graph declaration to use i32 edge weights:

        let mut graph = Graph::<_, i32>::new();
    

    causes the program to compile with no errors.