Error E0201 when implementing foreign trait for lo

2019-07-29 12:25发布

I'm trying to add the C type parameter to this code (playground):

use std::ops::Index;

struct ConnectionHandle(usize);
struct Connection<C>(C);

impl<C> Index<ConnectionHandle> for Vec<Connection<C>> {
    type Output = Connection<C>;
    fn index(&self, ch: ConnectionHandle) -> &Self::Output {
        &self[ch.0]
    }
}

But doing so causes this error message:

error[E0210]: type parameter `C` must be used as the type parameter for some local type (e.g. `MyStruct<C>`)
 --> src/lib.rs:6:1
  |
6 | impl<C> Index<ConnectionHandle> for Vec<Connection<C>> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `C` 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

Why isn't this allowed? Connection is local, so per the explanation for E0201 it seems like this should not result in orphans.

标签: rust traits
1条回答
smile是对你的礼貌
2楼-- · 2019-07-29 12:58

The problem is that Vec<Connection<C>> isn't considered a local type, because Vec isn't local (and isn't fundamental).

RFC 2451 will make it legal, however. An implementation was merged on January 4th, so it's not in stable yet, but it works with a recent nightly if the re_rebalance_coherence feature is enabled.

查看更多
登录 后发表回答