Hi everyone,
I have started learning rust like 10 days ago, I came across this while I was on conversions by documents.
I have implemented TryFrom on a struct, can I have two functions in an implementation like this?
use std::convert::TryFrom;
#[derive(Debug, PartialEq)]
struct EvenNumber(i32);
impl TryFrom<i32> for EvenNumber {
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
println!("even number!");
Ok(EvenNumber(value))
} else {
println!("Not an even number: {}", value);
Err(())
}
}
fn try_from2(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
fn main() {
let num1 = EvenNumber::try_from(8);
let num2 = EvenNumber::try_from2(8);
println!("{:?}", num1); // Output: even number!\nOk(EvenNumber(8))
println!("{:?}", num2); // Output: Ok(EvenNumber(8))
let even_number: EvenNumber = match EvenNumber::try_from2(8) {
Ok(dffs) => dffs,
Err(()) => {
println!("Not an even number!");
return;
}
};
println!("Even number: {:?}", even_number);
}outputs Even number: 8
(The first function is taken from rust by example, so its not me who gave first function try_form name as it is only accepting try_from), two functions are same except for the println difference .
In one case I wanted to have a println line in impl function and in other i wanted to print from main function, that was my intention or what i want to achieve.
In this case, the compiler is telling you that the method try_from2
is not part of the TryFrom
trait, therefore you can't add it to the impl block where you implemented the trait for your struct. this is what complier is sayin, yes but how do i know what methods are a part of TryFrom inorder to only use them, when i go into TryFrom fn try_from(value: T) -> Result<Self, Self::Error>;
, which means it only has one method as part to it?