How to implement trait for struct with lifecycle annotation

Time:2021-6-16

Problem description

The question comes from rust Chinese community, link:https://rust.cc/article?id=c8c9e40a-b27c-4…, the error code is as follows:

use std::str::FromStr;

pub struct Wrapper<'a>(&'a str);

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

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

Cause analysis

In section 10.3 of rust programming language“The compiler uses three rules to determine when references do not require explicit annotations. The first rule applies to the input lifecycle, and the last two rules apply to the output lifecycle. If the compiler checks these three rules and still has references that have not calculated their lifecycles, the compiler will stop and generate errors. These rules apply to FN definitions, as well as impl blocks.
The first rule is that every referenced parameter has its own lifecycle parameter.
The second rule is that if there is only one input lifecycle parameter, it is given all output lifecycle parametersfn foo<'a>(x: &'a i32) -> &'a i32
The third rule is if a method has multiple input lifecycle parameters, but one of them is because of the method  &self  or  &mut selfSo  self  Is assigned to all output lifecycle parameters. The third rule makes the method easier to read and write because it requires fewer symbols.
In the above example, FN from_ STR function obviously conforms to the second rule, that is to say, the life cycle of input parameter s: & STR is given as the life cycle of output. However, the type of self in the output parameter is structure wrapper, and wrapper has a life cycle limit. At this time, the compiler does not know how to judge, so an error is reported.
The original intention of the question subject is to implement fromstr trait for user-defined types, but it is obviously not possible here (the result of my analysis is that if there is a master who can directly implement fromstr trait here, please leave a message actively. Thank you very much). You can consider using other methods to realize similar functions (such as through methods).

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong