I want to implement FromStr
for a struct with a lifetime parameter:
use std::str::FromStr;
struct Foo<\'a> {
bar: &\'a str,
}
im
I don't believe that you can implement FromStr
in this case.
fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err>;
There's nothing in the trait definition that ties the lifetime of the input to the lifetime of the output.
Not a direct answer, but I'd just suggest making a constructor that accepts the reference:
struct Foo<'a> {
bar: &'a str
}
impl<'a> Foo<'a> {
fn new(s: &str) -> Foo {
Foo { bar: s }
}
}
pub fn main() {
let foo = Foo::new("foobar");
}
This has the side benefit of there not being any failure modes - no need to unwrap
.
You could also just implement From
:
struct Foo<'a> {
bar: &'a str,
}
impl<'a> From<&'a str> for Foo<'a> {
fn from(s: &'a str) -> Foo<'a> {
Foo { bar: s }
}
}
pub fn main() {
let foo: Foo = "foobar".into();
}