"Conflicting implimentations" for Into trait

SDL2 has this great method:

pub fn draw_points<'a, P: Into<&'a [Point]>>(
    &mut self,
    points: P
) -> Result<(), String>

I have my own struct CellNode and I'd like to be able to pass a Vector<CellNode> to draw_points. Here's my attempt:

use sdl2::rect::Point;
use core::convert::Into;

struct CellNode {
    //position in the form (x,y)
    pos: (i32, i32)
}

impl<Point, CellNode> Into<Point> for CellNode {
    fn into(self) -> Point {
        return Point::new(self.pos.0, self.pos.y);
    }
}

However, I get the errors: | 15 | impl<Point, CellNode> Into<Point> for CellNode { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: conflicting implementation in crate core: - impl<T, U> std::convert::Into<U> for T where U: std::convert::From<T>;

error[E0210]: type parameter `CellNode` must be usedas the type parameter for some local type     (e.g., `MyStruct<CellNode>`)
  --> src/lib/biology.rs:15:1
   |
15 | impl<Point, CellNode> Into<Point> for CellNode {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `CellNode` 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

Is this becausePoint already has an into? Did I declare it wrong? Help would be very appreciated :) thanks.

Posted Apr 11, 2019, 7:56 AM UTC

35
polaris64•

Here's an example which works. Note I'm declaring my own Point in place of the actual SDL version as I don't have the SDL2 library to hand.

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

impl Point {
    pub fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}

struct CellNode {
    //position in the form (x,y)
    pos: (i32, i32)
}

impl Into<Point> for CellNode {
    fn into(self) -> Point {
        return Point::new(self.pos.0, self.pos.1);
    }
}

fn main() {
    let point = Point::new(1, 2);
    let pt_from_cellnode: Point = (CellNode { pos: (1, 2) }).into();
    assert_eq!(point, pt_from_cellnode);
}

Hope that helps!

3
sellibitze•

The angle backets behind impl is just for introducing new parameters for generic implementations. Your implementation is not generic. No new parameters needed. You just want to implement Into<Point> for CellNode. Hence, you would write

impl Into<Point> for CellNode {
    ...
}

But this won't really be of much help, actually...

I have my own struct CellNode and I'd like to be able to pass a Vec<CellNode> to draw_points

That's not gonna work. How do you intend to create a &[Point] if you only have a Vec<CellNode>? If you make your CellNode convertible into a Point you won't automatically be able to convert &[CellNode] into &[Point]. That's a very different thing. So, unless you're fine with creating a temporary Vec<Point> based on your data, you should probably go with using SDL2's Point type directly.

2
SimDeBeauOP•

Mmm good point! I was more interested in figuring out how to do this than it being the best design. I’m trying to become more effective at leveraging rusts traits. It’s really just for debugging anyways though.

1
SimDeBeauOP•

Would it be possible to impl Into< Vec<Point> > for Vec<CellNode> ? I seem to be running into a similar problem. Would I have to create a wrapper struct or type to be able to do this? (I know it would be much more efficient to just store the points, but thats not my priority right now :) )

1
sellibitze•

It's not possible to write a function that takes a Vec<CellPoint> or a &[CellPoint] and produces a &[Point] as a result.

It's also not possible to implement Into in a way to turn an owned type like Vec<_> into a borrowed type like &[_] because that would be incompatible with the signature of Into::into.

You have to introduce a new Vec<Point> as an intermediate result and do some explicit borrowing get to &[Point].

fn make_sdl_point_vec(x: &[CellNode]) -> Vec<Point> {
    x.iter()
     .map(|cn| Point::new(cn.pos.0, cn.pos,1))
     .collect()
}

fn foo(p: &[CellNode]) {
    draw_points(make_sdl_point_vec(p).as_slice());
    //          ^                         ^
    // creates temporary Vec<Point>   borrows it
}

(untested)

I'm not familiar with the SDL2 crate. But it seems this definition of draw_points using Into is only useful, if you have some kind wrapper like this:

struct MyWrapper {
    data: Vec<Point>
}

impl<'a> Into<&'a [Point]> for &'a MyWrapper {
    fn into(self) -> &'a [Point] {
        self.data.as_slice()
    }
}

fn foo(mw: MyWrapper) {
    draw_points(&mw);
} //            ^-- borrow is important

(also untested)

So, even though I told you Into is not able to borrow self, we can implement Into for references which already are borrowed. :-)

To be honest, I find the definition of draw_points unfortunate because it wants to borrow something but uses Into which just converts something. That necessitates this rather complicated-looking Into implementation for references involving this mysterious lifetime parameter 'a. What they could have done instead is using AsRef instead of Into like this:

fn draw_points<P: AsRef<[Point]>>(points: P) {...}

struct MyWrapper {
    data: Vec<Point>
}

impl AsRef<[Point]> for MyWrapper {
    fn as_ref(&self) -> &[Point] {
        self.data.as_slice()
    }
}

fn foo(mw: MyWrapper) {
    draw_points(&mw); // works
    draw_points(mw); // works, too, but consumes the wrapper
}

(untested)

You might be wondering why the first call with &mw works even though we implemented AsRef only for MyWrapper and not &MyWrapper. But that's because the standard library already implements AsRef for references automatically which dispatches the as_ref call to the "inner type". :-)

2