Result<&mut T, T>
我尝试在a 内部匹配泛型const fn
,但编译器不允许。这需要能够删除作用域末尾的值,而这在 a 内部目前无法实现const fn
。
我稍微截断了一下代码,最终找到了这个片段。它仍然会报同样的错误,原因也一样,但不再是通用的了。
struct Dummy;
impl Drop for Dummy {
fn drop(&mut self) {
println!("dropped");
}
}
const fn const_match(result: Result<Dummy, ()>) -> Result<Dummy, ()> {
match result { //^^^^^^ the destructor for this type cannot be evaluated in constant functions
Ok(ok) => Ok(ok),
Err(err) => Err(err),
}
} // <- value is dropped here
编译器向我提供了以下错误消息:
error[E0493]: destructor of `Result<Dummy, ()>` cannot be evaluated at compile-time
--> <source>:9:22
|
9 | const fn const_match(result: Result<Dummy, ()>) -> Result<Dummy, ()> {
| ^^^^^^ the destructor for this type cannot be evaluated in constant functions
...
14 | }
| - value is dropped here
通过删除const
所有内容,编译可以完美进行,因此我创建了一个测试来检查该值是否真的在该函数内部被丢弃。
struct Dummy;
impl Drop for Dummy {
fn drop(&mut self) {
println!("dropped");
}
}
fn const_match(result: Result<Dummy, ()>) -> Result<Dummy, ()> {
match result {
Ok(ok) => Ok(ok),
Err(err) => Err(err),
}
}
fn main() {
let dummy = const_match(Ok(Dummy));
let err = const_match(Err(()));
std::mem::forget(dummy);
}
这是godbolt 链接,指向一个相同的代码示例。正如预期的那样,它没有任何输出,所以析构函数永远不会在 内部运行const_match
。
为什么析构函数需要能够运行?