gpt4 book ai didi

rust - 无法使用完全限定的语法来装箱未大小的类型

转载 作者:行者123 更新时间:2023-12-03 11:37:04 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How does the mechanism behind the creation of boxed traits work?

(2 个回答)


1年前关闭。




我尝试使用完全限定的语法对闭包进行装箱:

let x = Box::<SomeType>::new(some_value);
并期望它以与以下完全相同的方式工作:
let x: Box<SomeType> = Box::new(some_value);
即:编译。
相反,我得到一个编译器错误,说方法 new无法在 Box 上调用带有未调整大小的类型参数:
error[E0599]: no function or associated item named `new` found for struct `std::boxed::Box<dyn std::ops::FnMut() -> i32>` in the current scope
--> src/bin/observable_test/mod.rs:57:40
|
57 | let boxed = Box::<dyn FnMut() -> i32>::new(|| 0);
| ^^^ function or associated item not found in `std::boxed::Box<dyn std::ops::FnMut() -> i32>`
|
::: /mnt/data/william stanley/applications/rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:151:1
|
151 | pub trait FnMut<Args>: FnOnce<Args> {
| ----------------------------------- doesn't satisfy `dyn std::ops::FnMut() -> i32: std::marker::Sized`
|
= note: the method `new` exists but the following trait bounds were not satisfied:
`dyn std::ops::FnMut() -> i32: std::marker::Sized`
我认为这可能是由 impl 引起的的 Box的方法被声明为
impl<T> Box<T> {
...
}
因此隐式要求类型参数为 Sized ,但如果是这样的话,为什么要这样声明,为什么在不合格的情况下调用会起作用?

最佳答案

由于 Box 的方式,这确实会发生。的impl已声明,但如果您考虑一下,它确实是有道理的:new方法采用堆栈上的值,因此它必须是 Sized .

why does the call work when it isn't qualified?


这通常(但并非总是)有效,因为您提供给 new 的类型函数实际上不是未调整大小的 - 只有将它分配给具有更通用类型的变量时,它才会扩大到未调整大小的类型。
让我们重用您使用的示例,并找出您发布的第二个版本为什么有效:
let boxed: Box<dyn FnMut() -> i32> = Box::new(|| 0);
rust 引用 states :

A closure expression produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured variables.


这意味着传递给 new 的闭包类型实际上不是 dyn FnMut() -> i32 ,而是一个特定闭包的唯一类型,不能以任何方式写出,因此必须推断。
后面也有引用 notes :

All closure types implement Sized.


所以确实,类型一直是大小的,只是后来分配给类型为 dyn FnMut() -> i32 的变量已将原来的封闭类型扩大到更通用、尺寸较小的封闭类型。

关于rust - 无法使用完全限定的语法来装箱未大小的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63550683/

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