[EDIT] I am not looking for a solution to have a from_str()
(or a constructor) on my struct but rather I was just curious to see if there was a way to implement some native traits which don't take lifetime parameters.
I can indeed easily do without FromStr
but there might be some more complex cases when not implementing a Trait would lead to a much more complex / unstable solution
I am trying to implement the FromStr
trait for a structure which uses a lifetime parameter
use std::str::FromStr;
#[derive(Debug)]
struct Test<'s> {
value: &'s str,
}
impl<'s> Test<'s> {
fn new(val: &'s str) -> Self {
Test {
value: val,
}
}
}
impl<'s> FromStr for Test<'s> {
type Err = ();
fn from_str(t: &str) -> Result<Test<'s>, Self::Err> {
Ok(Test {
value: t,
})
}
}
fn main() {
let t1 = Test::new("test 1");
let t2 = Test::from_str("test 2");
println!("Test 1 = {:?}", &t1);
println!("Test 2 = {:?}", &t2);
}
As such it doesn't compile (rightfully so) and I get the following compilation error:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'s` due to conflicting requirements
So I tried to add lifetime requirements to the from_str()
function like that:
fn from_str<'t: 's>(t: &'t str) -> Result<Self, Self::Err> { ... }
But then again I have another compiler error (which I understand perfectly too)
error[E0195]: lifetime parameters or bounds on method `from_str` do not match the trait declaration
I can just not implement the trait and add the method to the structure's implementation but I was wondering whether it existed a way to do thing by implementing the trait?
PS: link to the code in a playground