0

Is it possible to implement the std::ops::Sub trait for slices in Rust? And if so how would I do that?

I tried the following:

use std::ops::Sub;

impl <'a, 'b, T> Sub<&'a [T]> for &'b [T] {
    type Output = Vec<T>;
    fn sub(self, rhs: &[T]) -> Vec<T> {
        difference(self, rhs)
    }
}

with difference having the signature:

difference<T: PartialEq + Copy>(xs: &[T], ys: &[T]) -> Vec<T>

compiling it results in the following error message:

error: type parameter `T` must be used as the type parameter for some local type 
    (e.g. `MyStruct<T>`); only traits defined in the current crate 
    can be implemented for a type parameter [E0210]
impl <'a, 'b, T> Sub<&'a [T]> for &'b [T] {
^

running then rust --explain E0210 to get further information I can kinda understand the problem, but I am confused about how the syntax would look like when using the struct MyType<T>(T); workaround described in the detailed explanation.

In difference to the question found How do I implement a trait I don't own for a type I don't own? my problem is I do not want this for vector types, but for slice types for which the syntax seems to be different enough that this answer is not really helpful.

Community
  • 1
  • 1
Alexander Battisti
  • 2,178
  • 2
  • 19
  • 24
  • It doesn't matter that it's a slice or a vec or a hashmap or a string or ...; if the trait and type aren't owned by you, you can't implement one for the other. – Shepmaster Jun 24 '16 at 16:20
  • so the accepted answer for a possible workaround by wrapping the types in a new struct type in "How do I implement a trait I don't own for a type I don't own?" is wrong? – Alexander Battisti Jun 24 '16 at 16:56
  • I don't understand how that conclusion was arrived at. Wrapping one type in another (the *newtype* pattern) means that *you own the wrapping type*. You can implement a trait you don't own for a type you do own. – Shepmaster Jun 24 '16 at 17:01
  • My question is about syntax only. How does the signature for the trait implementation look, when using the new type pattern for wrapping a slice type in the context of wanting to implement the Sub trait. – Alexander Battisti Jun 24 '16 at 17:21
  • Interesting - this question, as currently written, does not make that very clear. I would encourage you to ask a new question along the lines of "How do I create a newtype for a slice". Feel free to include the context from this question ("In order to implement `Sub` ..."). Make sure you include your attempt(s) at getting the syntax to work. I'm sure that question will get answered quickly. – Shepmaster Jun 24 '16 at 17:27
  • ok, thank you for the tip! – Alexander Battisti Jun 25 '16 at 15:51

0 Answers0