I am working on a way to programmatically new struct in memory and append it to the linked list.
The way I am doing is to new a struct, new a box pointing to it and wrap it by Option. Then I need to move the tail pointer down to the newly created one.
I want to previous node owns the next node. So the tail pointer has to 'borrow' the node.
#[derive(Debug)]
struct S {
next: Option<Box<S>>,
}
#[cfg(test)]
mod test {
use crate::tmp::S;
use std::borrow::Borrow;
#[test]
fn test_tmp() {
let mut s1 = S { next: None };
let mut tail = &s1;
// potentially within a loop as a linked list has multiple nodes
{
let mut s2 = S { next: None };
s1.next = Some(Box::new(s2));
// tail = &s2;
tail = s1.next.as_ref().unwrap();
}
println!("s1: {:?}", &s1);
println!("tail: {:?}", &tail);
}
}
The line commented out does not work as the owner has been moved to s1, I am fine with it.
tail = &s2
It's just so ugly but the next line works. Assuming if I have a struct that deeply wrapped and I want to borrow it. Does that mean I have to unwrap it deeply again?
tail = s1.next.as_ref().unwrap();
There must be some way to do it better. Any hints?
Rc
. Because of you want to mutate the data from the references you have, it is better to wrap it withMutex
. Playground - Akiner Alkan