【发布时间】:2016-06-29 17:41:23
【问题描述】:
为什么代码示例 1 可以编译,但示例 2 给出编译错误?
示例 1:
use std::ops::Index;
struct Bounded {
idx: usize,
}
impl Index<Bounded> for [i32; 4] {
type Output = i32;
fn index(&self, b: Bounded) -> &i32 {
unsafe { self.get_unchecked(b.idx) }
}
}
示例 2:
use std::ops::Index;
struct Bounded {
idx: usize,
}
impl<T> Index<Bounded> for [T; 4] {
type Output = T;
fn index(&self, b: Bounded) -> &T {
unsafe { self.get_unchecked(b.idx) }
}
}
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
--> src/main.rs:7:1
|
7 | impl<T> Index<Bounded> for [T; 4] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
|
= note: only traits defined in the current crate can be implemented for a type parameter
【问题讨论】:
-
这里的问题实际上是孤儿规则,而不是连贯规则:)。可以通过
rustc --explain E0210查看说明。 -
@kennytm:这不应该是一个答案(需要详细说明)吗?
标签: rust