无法在大小通用类型(E401)上的函数内部使用mem :: size_of创建常量

问题描述 投票:3回答:1

我有一个Rust程序,我一直在尝试使用const函数作为宏的替代方法,以在编译时生成各种常量(到目前为止进展良好),但是我遇到了一个障碍下面的代码段无法编译,因为size_of采用了通用参数,并且编译器说我不能使用函数签名中的参数:

const fn _IOC<T:Sized>(dir:u32, code:u8, nr:u8) -> u32 {
    // use of generic parameter from outer function (E0401)
    const size: usize = ::core::mem::size_of::<T>();

    (dir  << 30) | ((size as u32) << 16) | ((code as u32) << 8) | ((nr as u32))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let myioctl = _IOC::<[u8; 65]>(3, b'H', 0x06);
        assert_eq!(myioctl, 0xC0414806);
    }
}

这是错误:

error[E0401]: can't use generic parameters from outer function
 --> src/lib.rs:3:48
  |
1 | const fn _IOC<T:Sized>(dir:u32, code:u8, nr:u8) -> u32 {
  |               - type parameter from outer function
2 |     // use of generic parameter from outer function (E0401)
3 |     const size: usize = ::core::mem::size_of::<T>();
  |                                                ^ use of generic parameter from outer function

我不确定我是否理解this specific error为什么适用于上面的代码。我应该将其视为该语言当前不支持的编译器边缘情况,还是有办法使我看不到的这项工作?

generics rust constants sizeof
1个回答
3
投票

您不应该将size声明为const。它应该只是一个常规的不可变变量:

let size = ::core::mem::size_of::<T>();

Playground

© www.soinside.com 2019 - 2024. All rights reserved.