为什么对某些RefCell函数(而不是全部)定界? [英] Why is ?Sized a bound for certain RefCell functions, but not all?

查看:60
本文介绍了为什么对某些RefCell函数(而不是全部)定界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到对于某些功能(borrowborrow_stateborrow_mut),?Sized是类型参数T的绑定,但是,不是绑定到newinto_inner.如果我无法创建包含动态大小的内容(RefCell<T : ?Sized>)的RefCell,那么它具有可以对此类内容进行操作的功能有什么好处?

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?

推荐答案

该支持已添加了在一次提交中还添加了测试.我们可以查看这些测试,以了解预期如何使用它:

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);
}

由于编译器需要知道要在堆栈上分配的空间量,因此您始终需要具有绑定Sized的构造函数.一旦有了它,就可以强制使用动态大小的类型.

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.

这篇关于为什么对某些RefCell函数(而不是全部)定界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆