我有一个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为什么适用于上面的代码。我应该将其视为该语言当前不支持的编译器边缘情况,还是有办法使我看不到的这项工作?