【发布时间】:2023-01-11 09:03:41
【问题描述】:
假设存在以下代码
use core::any::Any;
enum Value {
Any(Box<dyn Any>),
Other, // placeholder, this code is adapted from mine
}
这段代码引发了一个我不太明白的诊断
impl<T: Any> TryFrom<Value> for T {
type Error = &'static str;
fn try_from(val: Value) -> Result<Self, Self::Error> {
if let Value::Any(any) = val {
if let Ok(down) = any.downcast::<T>() {
Ok(*down)
} else {
Err("incorrect type")
}
} else { Err("not an any") }
}
}
fn main() {
let res: Result<usize, &'static str> = Value::Any(Box::new(1usize)).try_into();
dbg!(res);
}
error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Value`)
--> src/main.rs:9:6
|
9 | impl<T: Any> TryFrom<Value> for T {
| ^ type parameter `T` must be covered by another type when it appears before the first local type (`Value`)
|
= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type
= note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last
我仍然不太明白“必须被另一种类型覆盖”是什么意思,也不明白“当它出现在第一个本地类型之前”是什么意思。
但是,如果我修改 impl 签名以将包含 T 的单元素元组作为目标,则 impl 不会引发错误,并且代码可以正常运行:
impl<T: Any> TryFrom<Value> for (T,) {
type Error = &'static str;
fn try_from(val: Value) -> Result<Self, Self::Error> {
if let Value::Any(any) = val {
if let Ok(down) = any.downcast::<T>() {
Ok((*down,))
} else {
Err("incorrect type")
}
} else { Err("not an any") }
}
}
fn main() {
let res: Result<(usize,), &'static str> = Value::Any(Box::new(1usize)).try_into();
dbg!(res);
}
单元素元组的实际用途是什么?
【问题讨论】:
-
您是否已阅读此问题中接受的答案:stackoverflow.com/a/63131661/4909009?
-
@Kendas 我有,除了它仍然没有向我解释 (T,) 如何解决这个问题,它没有在我的板条箱中定义,因为它是原始的。
标签: rust compiler-errors trait-objects