将petgraph Dot写入文件

3

我可能缺少一些非常基础的东西——我是 Rust 的新手。我正在尝试将 petgraph::dot::Dot 表示写入文件。

以下简短的代码示例无法编译:

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());
}

这是编译器的错误输出:

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`.

petgraph文档指出Dot实现了Display trait,我根据trait.Display doc中的示例代码编写了我的代码。

我可以通过将格式字符串更改为{:?}来使代码正常运行,但我认为那只能用于调试。有没有更好的方法来编写代码以实现相同的功能?

1个回答

3

Dot只有在边和节点权重都实现Display时才会实现Display

由于您的边是(),因此无法显示此图。

例如,将图声明更改为使用i32边权重:

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

使程序编译无误。


谢谢!更改为let mut graph = Graph::<_, i32>::new();就可以了——现在我知道文档中提到的Display边/节点实现是什么了。 - Ultrasaurus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接