我的Graph对象的生命周期/借用有问题。
fn main() {
let mut g = Graph {
nodePointer: &mut 0,
edgePointer: &mut 0,
nodes: &mut Vec::new(),
edges: &mut Vec::new(),
};
let node1 = g.add_node((1, 1));
let node2 = g.get_node(0);
}
pub struct Graph<'a> {
pub nodePointer: &'a mut usize,
pub edgePointer: &'a mut usize,
pub nodes: &'a mut Vec<Node>,
pub edges: &'a mut Vec<Edge>,
}
impl<'a> Graph<'a> {
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize {
let id: usize = *self.nodePointer;
self.nodes.push(Node {
id: id,
datum: data,
});
*self.nodePointer += 1;
return id;
}
pub fn get_node(&'a mut self, id: usize) -> &'a Node {
return &self.nodes[id];
}
pub fn add_edge(&'a mut self, source: u64, target: u64, weight: u16) -> usize {
let id: usize = *self.nodePointer;
self.edges.push(Edge {
id: id,
source,
target,
weight,
});
*self.edgePointer = *self.edgePointer + 1;
return id;
}
}
pub struct Node {
pub id: usize,
pub datum: (u64, u64),
}
pub struct Edge {
pub id: usize,
pub source: u64,
pub target: u64,
pub weight: u16,
}
Run Code Online (Sandbox Code Playgroud)
fn main() {
let mut g = Graph {
nodePointer: &mut 0,
edgePointer: &mut 0,
nodes: &mut Vec::new(),
edges: &mut Vec::new(),
};
let node1 = g.add_node((1, 1));
let node2 = g.get_node(0);
}
pub struct Graph<'a> {
pub nodePointer: &'a mut usize,
pub edgePointer: &'a mut usize,
pub nodes: &'a mut Vec<Node>,
pub edges: &'a mut Vec<Edge>,
}
impl<'a> Graph<'a> {
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize {
let id: usize = *self.nodePointer;
self.nodes.push(Node {
id: id,
datum: data,
});
*self.nodePointer += 1;
return id;
}
pub fn get_node(&'a mut self, id: usize) -> &'a Node {
return &self.nodes[id];
}
pub fn add_edge(&'a mut self, source: u64, target: u64, weight: u16) -> usize {
let id: usize = *self.nodePointer;
self.edges.push(Edge {
id: id,
source,
target,
weight,
});
*self.edgePointer = *self.edgePointer + 1;
return id;
}
}
pub struct Node {
pub id: usize,
pub datum: (u64, u64),
}
pub struct Edge {
pub id: usize,
pub source: u64,
pub target: u64,
pub weight: u16,
}
Run Code Online (Sandbox Code Playgroud)
您的问题源于滥用生命周期,特别是在您的签名中add_node:
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize
Run Code Online (Sandbox Code Playgroud)
在此签名中,您声明它add_node带有&'a mut self一个Graph<'a>; 换句话说,你是在告诉 Rust 这个方法需要对图进行可变借用,在图的生命周期结束之前不能删除'a。但由于图本身持有对图的引用,因此该引用将被删除的唯一时间是图本身被删除时。
由于add_node不需要您返回对结构中任何对象的引用,因此保持借用是无关紧要的。如果您更改add_node方法以删除显式生命周期:
pub fn add_node(&mut self, data: (u64, u64)) -> usize
Run Code Online (Sandbox Code Playgroud)
那么你的例子不再引发错误,因为add_node现在只是借用self直到它完成函数。(在幕后,这有效地创建了第二个生命周期'b并使签名变为&'b mut self)
见操场证明。
| 归档时间: |
|
| 查看次数: |
393 次 |
| 最近记录: |