From trait accept String, &str, and unsigned types

Hi, I tried to write a From trait to accept String, &str, and unsigned types. But compile failed. Any suggestion? Thanks!

pub struct Luhn {
    data: String,
}

impl<T> From<T> for Luhn {
    fn from(input: T) -> Self {
        Luhn {
            data: input.to_string(),
        }
    }
}

fn main () {
    let l1 = Luhn::from("123");
    let l2 = Luhn::from("123".to_string());
    let l3 = Luhn::from(123_u32);
    let l4 = Luhn::from(123_u16);
    let l5 = Luhn::from(123_u8);
}
error[E0119]: conflicting implementations of trait `std::convert::From<Luhn>` for type `Luhn`:
 --> src\main.rs:5:1
  |
5 | impl<T> From<T> for Luhn {
  | ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `core`:
          - impl<T> From<T> for T;

You're making use of the to_string() method which is part of the ToString trait, so you should constrain your implementation to types T that implement ToString:

impl<T: ToString> From<T> for Luhn { ... }

Playground.

2 Likes

Very clear! Thank you!!!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.