TryFrom conflict?
I'm trying to make a type that is limited to the values 1-9 for a sudoku solver.
It made sense to me to implement a TryFrom<u16>, but I thought that it might be even better to implement TryFrom for anything that can Into<u16>
TLDR implementation:
fn main() {
let a: board::Cell = board::Cell::try_from(1u16).unwrap();
println!("{:?}", a)
}
mod board {
#[derive(Debug)]
pub struct Cell(u16);
impl<T: Into<u16>> TryFrom<T> for Cell {
type Error = ();
fn try_from(value: T) -> Result<Self, Self::Error> {
let v: u16 = value.into();
if v > 0 && v < 10 {
return Ok(Cell(v))
}
Err(())
}
}
}
Compiler error:
error[E0119]: conflicting implementations of trait `std::convert::TryFrom<_>` for type `board::Cell`
--> src\main.rs:13:5
|
13 | impl<T: Into<u16>> TryFrom<T> for Cell {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<T, U> TryFrom<U> for T
where U: Into<T>;
I think that this implies that there is an:
impl<board:Cell, U> TryFrom<U> for board::Cell
where U: Into<board::Cell>
Is it that there's a potential for a conflict, or is there something that's already implementing Into<board::Cell> automatically? If it's a specific type, why not tell me?
My other thought would be to implement TryInto, but that would be implementing a foreign trait on a foreign type.
fn main() {
let a: board::Cell = board::Cell::try_from(1).unwrap();
println!("{:?}", a)
}
mod board {
#[derive(Debug)]
pub struct Cell(u16);
impl TryFrom<u16> for Cell {
type Error = ();
fn try_from(v:u16) -> Result<Cell, Self::Error> {
if v > 0 && v < 10 {
return Ok(Cell(v))
}
Err(())
}
}
}
works and is likely sufficient, but it's irritating me that I'm not fully understanding why my generic version isn't ok.
Posted Oct 15, 2022, 4:17 PM UTC
Interesting. I found this: https://github.com/rust-lang/rust/issues/50133
Thanks! Takes a bit of reading but explains it well.