gpt4 book ai didi

rust - 为什么 Weak::new() 不起作用而 Rc::downgrade() 起作用?

转载 作者:行者123 更新时间:2023-11-29 08:03:00 31 4
gpt4 key购买 nike

我正在创建一个返回 Weak 的函数对特征对象的引用。在找不到对象的情况下(它是一个查找函数),我想返回一个空的 Weak引用使用 Weak::new() :

use std::rc::{self, Rc, Weak};
use std::cell::RefCell;

pub trait Part {}

pub struct Blah {}

impl Part for Blah {}

fn main() {
let blah = Blah {};
lookup(Rc::new(RefCell::new(blah)));
}

fn lookup(part: Rc<RefCell<Part>>) -> Weak<RefCell<Part>> {
if true {
Rc::downgrade(&part)
} else {
Weak::new()
}
}

编译时出现如下错误:

error[E0277]: the trait bound `Part + 'static: std::marker::Sized` is not satisfied in `std::cell::RefCell<Part + 'static>`
--> <anon>:19:9
|
19 | Weak::new()
| ^^^^^^^^^ within `std::cell::RefCell<Part + 'static>`, the trait `std::marker::Sized` is not implemented for `Part + 'static`
|
= note: `Part + 'static` does not have a constant size known at compile-time
= note: required because it appears within the type `std::cell::RefCell<Part + 'static>`
= note: required by `<std::rc::Weak<T>>::new`

为什么我可以成功创建Weak<RefCell<Part>>来自 Rc::downgrade()但不能使用相同类型创建新的弱引用 Weak::new()

有没有办法让我注释Weak::new()帮助编译器还是我必须将其包装在 Option 中让用户知道找不到零件?

Working minimal example

最佳答案

Weak::new() 推断的类型是Weak<RefCell<Part>> , 和 Part部分无法创建,因为它是一个特征!

这就是 Sized 的内容错误就是这样。 trait 不是一个具体的结构,它在编译时不知道大小,因此编译器不知道要分配多少空间。

Why is it that I can successfully create a Weak<RefCell<Part>> from Rc::downgrade()

是因为Rc<RefCell<Part>>指向一个已经分配的结构。编译器可以使用特征指针引用它,即使它不知道它是否是 Blah。或 Part 的一些其他实现特质。

Is there a way for me to annotate Weak::new() to help the compiler

你确实可以注释Weak::new() , 将编译器指向 Part 的实现你想要实例化,像这样:

use std::rc::{Rc, Weak};
use std::cell::RefCell;

pub trait Part {}

pub struct Blah {}

impl Part for Blah {}

fn main() {
let blah = Blah {};
lookup(Rc::new(RefCell::new(blah)));
}

fn lookup(part: Rc<RefCell<Part>>) -> Weak<RefCell<Part>> {
if true {
Rc::downgrade(&part)
} else {
Weak::<RefCell<Blah>>::new()
}
}

关于rust - 为什么 Weak::new() 不起作用而 Rc::downgrade() 起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573591/

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