rust中的泛型常量表达式,使用bool和usize

djmepvbi  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(202)

我想定义一个类似于

  1. pub struct ArInt<const W: usize, const S: bool>
  2. {
  3. iarr : [i32; {(W + 31 + (!S))/32}],
  4. }

我得到一个编译错误:

  1. --> src/ar_int.rs:7:27
  2. |
  3. 7 | iarr : [i32; {(W + 31 + (!S))/32}],
  4. | ^ no implementation for `usize + bool`
  5. |
  6. = help: the trait `Add<bool>` is not implemented for `usize`
  7. = help: the following other types implement trait `Add<Rhs>`:
  8. <&'a usize as Add<usize>>
  9. <&usize as Add<&usize>>
  10. <usize as Add<&usize>>
  11. <usize as Add>

我做了如下修改

  1. pub struct ArInt<const W: usize, const S: bool>
  2. {
  3. iarr : [i32; {(W + 31 + (!S) as usize)/32}],
  4. }

我仍然得到一个错误:

  1. error: unconstrained generic constant
  2. --> src/ar_int.rs:7:12
  3. |
  4. 7 | iarr : [i32; {(W + 31 + (!S) as usize)/32}],
  5. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  6. |
  7. = help: try adding a `where` bound using this expression: `where [(); {(W + 31 + (!S) as usize)/32}]:`

有办法让它工作吗?
PS:我有#![feature(generic_const_exprs)]
谢谢

**更新:**如@Caesar所述,按照编译器给出的提示即可。

  1. pub struct ArInt<const W: usize, const S: bool>
  2. where [(); {(W + 31 + (!S) as usize)/32}]:
  3. {
  4. iarr : [i32; {(W + 31 + (!S) as usize)/32}],
  5. }

但谁能解释一下“where”这句话的意思?看起来很奇怪
谢谢

58wvjzkj

58wvjzkj1#

在本文中,where [(); {(W + 31 + (!S) as usize)/32}]:表示或多或少:“* 其中[(); {(W + 31 + (!S) as usize)/32}]是可能的类型 *"。这使得允许的值从一开始就很清楚。例如,你不能这样做:

  1. let f: ArInt<usize::MAX, true>;

因为usize::MAX + 31会溢出。where子句使该约束可见,而无需查看实现细节。

相关问题