Hi guys I am very new to rust (2 days so far) and I think I don't understand the borrowing and lifecycle right.
I want to have "global" vectors into which struct methods are able to push.
This is what I have so far:
#[derive(Debug)]
struct Vector {
x: f64,
y: f64,
}
impl Vector {
fn new(x: f64, y: f64) -> Self {
Self {
x: x,
y: y,
}
}
}
#[derive(Debug)]
struct Edge<'a> {
vertices: [&'a Vector; 2],
}
impl<'a> Edge<'a> {
pub fn new(vertices: &'a mut Vec<Vector>, x_a: f64, y_a: f64, x_b: f64, y_b: f64) -> Self {
vertices.push(Vector::new(x_a, y_a));
vertices.push(Vector::new(x_b, y_b));
Self {
vertices: [
&vertices[vertices.len() - 2],
&vertices[vertices.len() - 1],
]
}
}
}
#[derive(Debug)]
struct Face<'a> {
edges: [&'a Edge<'a>; 4],
}
impl<'a> Face<'a> {
pub fn new(edges: &'a mut Vec<Edge<'a>>, vertices: &'a mut Vec<Vector>) -> Self {
for _ in 0..4 {
edges.push(Edge::new(vertices, 1.0, 2.0, 1.0, 3.0));
}
Self {
edges: [
&edges[edges.len() - 4],
&edges[edges.len() - 3],
&edges[edges.len() - 2],
&edges[edges.len() - 1],
]
}
}
}
fn main() {
let mut vertices: Vec<Vector> = Vec::new();
let mut edges: Vec<Edge> = Vec::new();
let face = Face::new(&mut edges, &mut vertices);
println!("{:?}", face);
}
The error reads like this:
cannot borrow `*vertices` as mutable more than once at a time
`*vertices` was mutably borrowed here in the previous iteration of the looprustcE0499
main.rs(39, 6): lifetime `'a` defined here
main.rs(42, 24): argument requires that `*vertices` is borrowed for `'a`
|
39 | impl<'a> Face<'a> {
| -- lifetime `'a` defined here
...
42 | edges.push(Edge::new(vertices, 1.0, 2.0, 1.0, 3.0));
| ----------^^^^^^^^---------------------
| | |
| | `*vertices` was mutably borrowed here in the previous iteration of the loop
| argument requires that `*vertices` is borrowed for `'a`
I think this kind of question is similar to a lot of other questions in this forum, but having an answer depending on my own code would be nice. I tried some wired stuff with RefCell too, but I dont really understand the concept.
Thank you very much!