我想创建一个Rc<str>
,因为我想减少访问Rc<String>
所需的两个指针的间接性.我需要使用Rc
,因为我确实拥有共同的所有权.我详细介绍了关于字符串类型的another question个更具体的问题.
pub struct Rc<T: ?Sized> { /* fields omitted */ }
我还听说Rust 1.2将提供适当的支持,用于在Rc
中存储未大小的类型,但我不确定这与1.1有何不同.
以str
case 为例,my naive attempt(也是从String
构建的this)出现以下故障:
use std::rc::Rc;
fn main() {
let a: &str = "test";
let b: Rc<str> = Rc::new(*a);
println!("{}", b);
}
error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
--> src/main.rs:5:22
|
5 | let b: Rc<str> = Rc::new(*a);
| ^^^^^^^ `str` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `str`
= note: required by `<std::rc::Rc<T>>::new`
很明显,为了创建一个Rc<str>
,我需要复制整个字符串:RcBox
本身就是一个非大小的类型,将字符串本身存储在弱指针和强指针旁边——上面的简单代码甚至没有意义.
有人告诉我,不能实例化这样的类型,而是用大小为T
的Rc<T>
来实例化,然后将其强制为非大小的类型.给出的示例是存储一个trait对象:首先创建Rc<ConcreteType>
,然后强制为Rc<Trait>
.但这也没有意义:this和this都不起作用(而且你也不能强迫&str
或String
到str
).