I'm learning how much this piece of code can be improved

This is mainly due to the push_item function which I see may have extra steps.

use std::{cell::RefCell, rc::Rc};

#[derive(Debug)]
struct Value {
  value: i32,
}

#[derive(Debug)]
struct List {
  index: usize,
  list: Rc<RefCell<Vec<Value>>>,
}

fn push_item(
  ptr: &Rc<RefCell<List>>,
  val: i32,
) {
  let ptr_ref = ptr.as_ref().borrow();
  let list_rc = Rc::clone(&ptr_ref.list);
  let mut list_ref = list_rc.as_ref().borrow_mut();
  list_ref.push(Value { value: val });
}

fn main() {
  println!("Hello, world!");

  let list = List {
    index: 0,
    list: Rc::new(RefCell::new(vec![])),
  };

  let rclist = Rc::new(RefCell::new(list));

  let mut val = 0;

  loop {
    if val >= 10 {
      break;
    }

    push_item(&rclist, val);

    val += 1;
  }

  println!("value (p): {:#?}", rclist);
}

This isn't valid Rust code.

Check out the pinned formatting guide. Wrap code in code blocks:

```
rust code goes here
```

thanks

compiles and runs fine. :man_shrugging:

It's a little unclear what you're asking. This is about as concise as it can get:

fn push_item(
  ptr: Rc<RefCell<List>>,
  val: i32,
) {
  ptr.borrow_mut().list.borrow_mut().push(Value { value: val });
}
1 Like

Sure, after being edited...

When you don't put your code into code blocks, parts of it get eaten up as invalid HTML.

1 Like


sure

You don't need to clone the Rc.

You don't need to be explicit about .as_ref() thanks to method resolution.[1]


  1. But if the compiler ever suggests importing the Borrow or BorrowMut traits, you probably shouldn't; those will interfere with the method resolution being able to find your RefCells. ↩ī¸Ž

Thank you very much, now I understand the extra steps I took. :+1: