Home Ask Login Register

Developers Planet

Your answer is one click away!

Matt February 2016

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

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?


Shepmaster February 2016

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;

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.

Post Status

Asked in February 2016
Viewed 2,216 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life