E0506 cannot assign because it is borrowed


#1

Hi,
I have this code
https://play.rust-lang.org/?gist=7fb869fefd7ee66b3a551b84ad02121c&version=stable&backtrace=0
Which is this

struct A<'a> {
data: u32,
all: Vec<&'a A<'a>>
}

impl<'a> A<'a> {
fn new() -> A<'a> {
A { data: 0, all: Vec::new() }
}
}

fn main() {
let mut a = A::new();
let mut b = A::new();
//a.all.push(&b);
b.all.push(&a);
println!(" {}", b.all[0].data);
a.data = 2;
println!(" {}", b.all[0].data);
}

I need a, b mutable maybe I have to use Rc or Weak.

Thanks.


#2

If data is the only thing you need to modify, you could wrap it in a Cell. For more complicated (non-Copy) types, use RefCell instead.


#3

Thanks. I tested the code
https://play.rust-lang.org/?gist=3843630fd6fc6bd1323afb6283d34e7a&version=stable&backtrace=0


#4

https://play.rust-lang.org/?gist=eda4f1c67c4a927f383eafbf1f58b41c&version=stable&backtrace=0 works, technically speaking, but it’s extremely limited.

See http://smallcultfollowing.com/babysteps/blog/2015/04/06/modeling-graphs-in-rust-using-vector-indices/ and https://github.com/nrc/r4cppp/blob/master/graphs/README.md for practical advice how to build graph data structures in Rust.


#5

Thanks for the example for line 15.