繁体   English   中英

为什么弧<dyn fn(dyn fnonce(&mut [u8]), usize) -> Result&lt;(), ()&gt; + Send + Sync&gt; 在编译时不知道 syze</dyn>

[英]Why Arc<dyn Fn(dyn FnOnce(&mut [u8]), usize) -> Result<(), ()> + Send + Sync> doesn't have syze known at compile time

use std::sync::Arc;
pub type A = Arc<dyn Fn(dyn FnOnce(&mut [u8]), usize) -> Result<(), ()> + Send + Sync>;

pub struct B {
    a: A,
}

   Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `(dyn for<'r> FnOnce(&'r mut [u8]) + 'static)` cannot be known at compilation time
 --> src/lib.rs:5:8
  |
5 |     a: A,
  |        ^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `(dyn for<'r> FnOnce(&'r mut [u8]) + 'static)`
  = note: only the last element of a tuple may have a dynamically sized type

我认为Arc在编译时知道大小。 dyn Fn有,至少当我做pub type A = Arc<dyn Fn() -> Result<(), ()> + Send + Sync>; . 但是,当我将dyn FnOnce(&mut [u8])放入dyn Dn时,无法知道大小。

为什么pub type A = Arc<dyn Fn() -> Result<(), ()> + Send + Sync>; 可以,但不是pub type A = Arc<dyn Fn(dyn FnOnce(&mut [u8]), usize) -> Result<(), ()> + Send + Sync>; ?

该错误有点无用,因为它会将您引导到类型的错误部分。

dyn Fn有 [大小]

像任何“裸”特征 object 一样, dyn Fn没有大小。 但是这没关系,因为Arc<T>不需要T: Sized

问题是dyn FnOnce(&mut [u8])没有大小,所以你不能有Fn(dyn FnOnce(&mut [u8]), usize) 不允许 function 参数没有大小。

使 function 参数Sized可以解决问题,例如

pub type A = Arc<dyn Fn(&dyn FnOnce(&mut [u8]), usize) -> Result<(), ()> + Send + Sync>;
//                      ^--- added &

值得报告一个错误,以便可以改进此错误消息。

错误消息(锈 1.50)

help: the trait `Sized` is not implemented for `(dyn for<'r> FnOnce(&'r mut [u8]) + 'static)`
note: only the last element of a tuple may have a dynamically sized type

FnOnce trait 将 Args 作为泛型类型,并且 Args 可以在内部从元组转换(我的猜测:)。

但是,我们不能像 (dynamic sized, sized) 这样的元组

您的代码可以使用 &dyn FnOnce (调整大小)或交换参数位置来修复

pub type A = Arc<dyn Fn(&dyn FnOnce(&mut [u8]), usize) -> Result<(), ()> + Send + Sync>;
// or
pub type A = Arc<dyn Fn(usize, dyn FnOnce(&mut [u8])) -> Result<(), ()> + Send + Sync>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM