【问题标题】:What's the alternative to u32::BITS in a const?const 中 u32::BITS 的替代方法是什么?
【发布时间】:2016-03-29 13:15:04
【问题描述】:

我有一些代码可以做到这一点:

const MY_CRAZY_CONSTANT: u32 = 1 << (u32::BITS - 1); 

我尝试使用 Rust nightly (2016-03-29) 编译它,但它失败并显示以下消息:

error: no associated item named `BITS` found for type `u32` in the current scope

我看到它已被弃用,我看到有一个 RFC (Sizeof, alignof, offsetof, typeof #591) 谈论添加 sizeof 关键字等,但已关闭:推迟。

我猜夜间频道的弃用已经实现,因为它已被删除,我知道我可以执行以下操作,但要做到这一点,我需要删除我的 const,我不想这样做。

mem::size_of::<u32>() * 8

那么,现在是我必须删除我的 const 并重新构建我的代码还是有其他方法来实现我最初的目标?

【问题讨论】:

    标签: rust


    【解决方案1】:

    一般的答案是定义自己的常量:

    const U32_BITS: usize = 32;
    

    对于usize::BITSisize::BITS 的特殊情况,您将需要使用条件编译。

    #[cfg(target_pointer_width = "32")]
    const USIZE_BITS: usize = 32;
    #[cfg(target_pointer_width = "64")]
    const USIZE_BITS: usize = 64;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多