【发布时间】:2022-01-23 05:33:52
【问题描述】:
我在 Rust 代码中经常看到这一点。以下是标准库中的一些示例:
impl<T> const Default for Option<T> {...}
impl const From<char> for u64 {...}
impl const 是什么?
【问题讨论】:
标签: rust syntax constants traits
我在 Rust 代码中经常看到这一点。以下是标准库中的一些示例:
impl<T> const Default for Option<T> {...}
impl const From<char> for u64 {...}
impl const 是什么?
【问题讨论】:
标签: rust syntax constants traits
如果你运行代码:
trait Example {}
impl const Example for u8 {}
您会收到一条错误消息,指出您正确的方向:
error[E0658]: const trait impls are experimental
--> src/lib.rs:3:6
|
3 | impl const Example for u8 {}
| ^^^^^
|
= note: see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information
= help: add `#![feature(const_trait_impl)]` to the crate attributes to enable
Issue 67792 是RFC 2632 — Calling methods on generic parameters of const fns 的跟踪问题。
这是一种不稳定 语法,允许定义可在const 上下文中使用的特征。它与同样 unstable ~const 可用于 trait bound 的语法配对:
// 1.59.0-nightly (2021-12-20 23f69235ad2eb9b44ac1)
#![feature(const_fn_trait_bound)]
#![feature(const_trait_impl)]
trait Example {
fn usage(&self) -> Self;
}
impl const Example for u8 {
fn usage(&self) -> Self {
42
}
}
const fn demo<T: ~const Example>(v: &T) -> T {
v.usage()
}
const VALUE: u8 = demo(&1);
fn main() {
dbg!(VALUE);
}
【讨论】: