Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ?Sized a bound for certain RefCell functions, but not all?

Tags:

memory

rust

I noticed that ?Sized is a bound on the type parameter T for some functions (borrow, borrow_state, and borrow_mut), however, it is not a bound for new or into_inner. If I can't create a RefCell containing something that is dynamically sized (RefCell<T : ?Sized>), then what good is it having functions that can operate on such a thing?

like image 789
Matt Avatar asked Sep 26 '22 10:09

Matt


1 Answers

That support was added in a commit that also added tests. We can look at those tests to see how it was expected to be used:

use std::cell::RefCell;

#[test]
fn refcell_unsized() {
    let cell: &RefCell<[i32]> = &RefCell::new([1, 2, 3]);
    {
        let b = &mut *cell.borrow_mut();
        b[0] = 4;
        b[2] = 5;
    }
    let comp: &mut [i32] = &mut [4, 2, 5];
    assert_eq!(&*cell.borrow(), comp);
}

You always need to have a constructor with a Sized bound as the compiler needs to know the amount of space to allocate on the stack. Once you have that, you can then coerce to a dynamically-sized type.

like image 90
Shepmaster Avatar answered Oct 27 '22 14:10

Shepmaster