0

I'm trying to implement From<T> where T implements Display for my custom type Cell:

use std::borrow::Cow;
use std::fmt::{Display, Formatter, Result};

pub struct TableCell<'data> {
    pub data: Cow<'data, str>,
    pub col_span: usize,
    pub pad_content: bool,
}

impl<'data> TableCell<'data> {
    pub fn new<T>(data: T) -> TableCell<'data>
    where
        T: ToString,
    {
        return TableCell {
            data: data.to_string().into(),
            col_span: 1,
            pad_content: true,
        };
    }
}

impl<'data> Display for TableCell<'data> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self.data)
    }
}

impl<'data, T> From<T> for TableCell<'data>
where
    T: ToString,
{
    fn from(other: T) -> Self {
        return TableCell::new(other);
    }
}

fn main() {
    println!("Hello, world!");
}

I keep running into the following error:

error[E0119]: conflicting implementations of trait `std::convert::From<TableCell<'_>>` for type `TableCell<'_>`:
  --> src/main.rs:29:1
   |
29 | / impl<'data, T> From<T> for TableCell<'data>
30 | | where
31 | |     T: ToString,
32 | | {
...  |
35 | |     }
36 | | }
   | |_^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> std::convert::From<T> for T;

Is this sort of thing possible, or do I need to implement From for specific types?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rykeeboy
  • 645
  • 2
  • 8
  • 22
  • You can't `impl Trait for Type` if neither `Trait` nor `Type` are defined in your crate. – PitaJ Nov 11 '18 at 00:55
  • @PitaJ It looks like OP has defined their own type named `Cell`. std's `Cell` doesn't have a lifetime parameter. – Francis Gagné Nov 11 '18 at 02:34
  • Yeah, Cell is a type defined by me – rykeeboy Nov 11 '18 at 02:53
  • Here is a playground that reproduces the problem: https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=0ba74d4022cbe87ec3103ca19b6bee42 If I remove the Display impl for TableCell it works but I don't understand why – rykeeboy Nov 11 '18 at 03:16

0 Answers0