Rust lifetimes and reference, how to achieve two things pointing to each other?


#1
use std::vec;

enum Norm{
	L(u32),
	Infinity,
}

enum Dimensions{
	One(u8),
	Two(u8,u8),
	Three(u8,u8,u8),
	Four(u8,u8,u8,u8),
	All,
}

enum Operator {
	None,
	Add,
	Negation,
	Multiply,
	Inverse,
	DotMultiply,
	DotInverse,
	Power(f64),
        Transpose,
        Diagonal,
        VerticalConcatenation,
	HorizontalConcatenation,
        Subindex(u32,u32,u32,u32),
        Reshape(u32,u32),
        Replicate(u32,u32),
        Norm,
        Sum(Dimensions),
        Abs,
        Exp,
        Log,
        Sigm,
        Mean,
        Std,
        Sin,
        Sinh,
        Cos,
        Cosh,
        Tan,
        Tanh,
    }


pub struct GraphBuilder<'a>{
	counter: u32,
	nodes: Vec<Node<'a>>,
	warn: bool,
}

impl<'a> GraphBuilder<'a>{
	pub fn new(warn: bool) -> GraphBuilder<'a> {
        	GraphBuilder { warn:warn, counter:0, nodes: vec![]}
	}

	pub fn createVariable(&'a mut self, dims: &[u32; 2])-> &Node<'a>{
		self.nodes.push(Node{builder: self, id: self.counter, idRelated: Option::None, dims: dims.clone(), name: format!("Autogenerated[{}]",self.counter), operator: Operator::None,
				broadcasts: [false; 2], parents: vec![], children: vec![]});
		self.counter += 1;
		&self.nodes[self.nodes.len()-1]
	}
	
	fn createInternalVariable
}

impl<'a> Default for GraphBuilder<'a>{
	fn default() -> GraphBuilder<'a> {
		GraphBuilder { warn:true, counter:0, nodes: vec![]}
	}
}

pub struct Node<'a>{
	builder: &'a GraphBuilder<'a>,
	id: u32,
	idRelated: Option<u32>,
	dims: [u32; 2],
	name: String,
	operator: Operator,
	broadcasts: [bool; 2],
	parents: Vec<&'a Node<'a>>,
	children: Vec<&'a Node<'a>>,
}

impl<'a> Node<'a>{
	fn print(&self) {
		println!("SA{}", self.parents[0].id);
		println!("SA{}", self.children[0].id);
	}
}

This is the sample code I want to figure out how to do in Rust. The compilation error is that in createVariable error: cannot assign to self.counter because it is borrowed. And that’s fine because I know why this happens. Question is how to fix it or any ideas of a better approach. To explain, later I will need to call from the Node struct builder.createVariable, that is why I need a reference to it, yet the builder itself should contain all the nodes and they will be operated and returned only by references.


#2

The best way is probably to store indices into an array of nodes. You could probably also do it by using RC, but then you’re responsible for preventing memory leaks.