gpt4 book ai didi

rust - Rust Petgraph WASM项目,尝试将struct与Graph属性一起使用,但需要2个参数

转载 作者:行者123 更新时间:2023-12-03 11:28:59 33 4
gpt4 key购买 nike

我对Rust还是很陌生,所以这可能是一个非常菜鸟的问题。

我正在尝试使用rust-> wasm创建一个Web应用程序。尝试按照教程https://rustwasm.github.io/docs/book/introduction.html进行操作,并尝试使用包装箱包“petgraph”
我想出了以下几点

use petgraph::graph::Graph;
#[wasm_bindgen]
pub struct TreeStructure {
directed_graph: Graph
}
#[wasm_bindgen]
impl TreeStructure {
pub fn new() -> TreeStructure {
TreeStructure {
directed_graph: Graph::<&str, &str>::new()
}
}
pub fn addNode(&mut self, newNode: &str) {
let findIndex = self.findNode(newNode);
if findIndex < 0 {
self.directed_graph.add_node(newNode);
} else {
alert("cant add, this {} already exist in the nodes", newNode);
}
}

pub fn removeNode(&mut self, toRemoveNode: &str) {
let findIndex = self.findNode(toRemoveNode);
if findIndex > -1 {
self.directed_graph.remove_node(toRemoveNode);
} else {
alert("cant remove, cannot find {} in the nodes", toRemoveNode);
}
}

pub fn addEdge(&mut self, fromNode: &str, toNode: &str) {
let fromIndex = self.findNode(fromNode);
let toIndex = self.findNode(toNode);
if fromIndex > -1 && toIndex > -1 {
let alreadyEdged = self.directed_graph.contains_edge(fromIndex, toIndex);
if !alreadyEdged {
self.directed_graph.add_edge(fromIndex, toIndex, "");
} else {
alert("edge already exist from {} to {}", fromNode, toNode);
}
}
}

pub fn getNeighbors(&self, checkNode: &str) -> Array {
let checkIndex = self.findNode(checkNode);
if checkIndex < 0 {
return vec![].into_inter().collect();
}
self.directed_graph.neighbors_directed(checkIndex).collect();
}
}
impl TreeStructure {
pub fn findNode(&self, nodeToFind: &str) -> i32 {
let findIndex = self.directed_graph.node_indices().collect::<Vec<_>>().iter().position(|&r| r == nodeToFind);
match findIndex {
Some(x) => x,
None => -1
}
}
}

但这给了我编译错误

error[E0107]: wrong number of type arguments: expected at least 2, found 0
--> src/lib.rs:25:25
|
25 | directed_graph: Graph
| ^^^^^ expected at least 2 type arguments

阅读 https://docs.rs/petgraph/0.5.0/petgraph/graph/struct.Graph.html
然后我尝试了
use petgraph::graph::Node;
use petgraph::graph::Edge;
pub struct TreeStructure<N: Node, E: Edge> {
directed_graph: Graph<N, E>
}

但是然后它说wasm-bindgen不支持该语法?我在这里该怎么办?

最佳答案

鉴于您的new函数将Graph::<&str, &str>放入directed_graph中,这也是您还应在声明中使用的内容:

pub struct TreeStructure {
directed_graph: Graph<&str, &str>,
}

但是,这需要您指定生存期。我对wasm不够熟悉,无法说出哪种方法最好(而且取决于您在图表中的确切位置),但是您可能需要使用 'static生存期:
pub struct TreeStructure {
directed_graph: Graph<&'static str, & 'static str>,
}

这还需要您将 'static生命周期赋予您的方法参数。否则,您将需要移至拥有的字符串:
pub struct TreeStructure {
directed_graph: Graph<String, String>,
}

再次对您的方法进行适当的更改。

关于rust - Rust Petgraph WASM项目,尝试将struct与Graph属性一起使用,但需要2个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61494301/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com