Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error E0201 when implementing foreign trait for local type with parameter

Tags:

rust

traits

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.

like image 487
djc Avatar asked Apr 27 '26 23:04

djc


1 Answers

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.

like image 114
Francis Gagné Avatar answered Apr 30 '26 11:04

Francis Gagné



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!