gpt4 book ai didi

rust - 如何构建 Rc 或 Rc<[T]>?

转载 作者:行者123 更新时间:2023-11-29 07:41:59 27 4
gpt4 key购买 nike

我想创建一个 Rc<str>因为我想减少跟踪访问 Rc<String> 的 2 个指针的间接访问需要。我需要使用 Rc因为我确实拥有共享所有权。我在 another question 中详细说明关于我的字符串类型的更具体的问题。

RC has a ?Sized bound :

pub struct Rc<T: ?Sized> { /* fields omitted */ }

我还听说 Rust 1.2 将适当支持在 Rc 中存储未确定大小的类型。 ,但我不确定这与 1.1 有何不同。

str以案例为例,我的naive attempt (还有 this 用于从 String 构建)失败:

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本身就是一个未调整大小的类型,将字符串本身与弱指针和强指针一起存储——上面的天真代码甚至没有意义。

有人告诉我不能实例化这种类型,而是实例化一个 Rc<T>尺寸 T然后将其强制为未指定大小的类型。给出的示例用于存储特征对象:首先创建 Rc<ConcreteType>然后强制到Rc<Trait> .但这也没有意义:this 都没有。也不this工作(而且你不能强制从 &strStringstr 无论如何)。

最佳答案

从 Rust 1.21.0 开始,由 RFC 1845 强制执行, 创建一个 Rc<str>Arc<str>现在可以:

use std::rc::Rc;
use std::sync::Arc;

fn main() {
let a: &str = "hello world";
let b: Rc<str> = Rc::from(a);
println!("{}", b);

// or equivalently:
let b: Rc<str> = a.into();
println!("{}", b);

// we can also do this for Arc,
let a: &str = "hello world";
let b: Arc<str> = Arc::from(a);
println!("{}", b);
}

( Playground )

参见 <Rc as From<&str>> <Arc as From<&str>> .

关于rust - 如何构建 Rc<str> 或 Rc<[T]>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31685697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com