How do I implement FromStr with a concrete lifetime?

后端 未结 1 1427
梦毁少年i
梦毁少年i 2020-12-20 23:52

I want to implement FromStr for a struct with a lifetime parameter:

use std::str::FromStr;

struct Foo<\'a> {
    bar: &\'a str,
}

im         


        
相关标签:
1条回答
  • 2020-12-21 00:15

    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();
    }
    
    0 讨论(0)
提交回复
热议问题