Lifetime struct ,how to impl From_str

use std::str::FromStr;

fn t() {
    let a = A {
        v: "abc",
    println!("{:?} ", a);

struct A<'a> {
    v: &'a str,

impl<'a> FromStr for A<'_> {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(A { v: s })

how to update? it fail . i don't how to do . and if the struct A has another reference type ? and how to do ?

i notice the form_str trait is not support the lifetime . if i don't impl the trait .
i write a method . return the Result or Option . can it include the lifetime ?

You cannot do this with FromStr. It will work if you write a function on A or implement From<&'a str> for A<'a> however.

1 Like

The relevant paragraph from the docs:

FromStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromStr, but not a &i32. You can parse a struct that contains an i32, but not one that contains an &i32.

1 Like

You should not put temporary loans in structs. & is not for storing "by reference". It prevents storing data in structs.

Store strings as String, and you'll be able to implement FromStr easily, without scope of temporary variables limiting what can you do with the struct.

1 Like