【问题标题】:Error E0201 when implementing foreign trait for local type with parameter使用参数为本地类型实现外部特征时出现错误 E0201
【发布时间】:2019-01-28 11:27:16
【问题描述】:

我正在尝试将C 类型参数添加到此代码(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]
    }
}

但这样做会导致此错误消息:

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

为什么不允许这样做? Connection 是本地的,所以根据 E0201 的解释,这似乎不应该导致孤儿。

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    问题在于Vec&lt;Connection&lt;C&gt;&gt; 不被视为本地类型,因为Vec 不是本地类型(也不是fundamental)。

    RFC 2451 将使其合法,但是。 An implementation was merged 1 月 4 日,所以它还不稳定,但如果启用了 re_rebalance_coherence 功能,它可以与最近的夜间活动一起使用。

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 2018-04-11
      • 2019-12-08
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2013-06-25
      相关资源
      最近更新 更多