Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* the tuple is a reference, which has lifetime till Context */
- struct Context<'b>(&'b str);
- /* Parser's context is reference, which is a type of Context */
- /* (reference to context), and (reference to str_slice in context)
- has has same lifetime of 'a
- */
- struct Parser<'a> {
- context: &'a Context<'a>,
- }
- impl<'a> Parser<'a> {
- fn parse(&self) -> Result<(), &str> {
- Err(&self.context.0[1..])
- }
- }
- /* check the param, parse_context takes ownership of Context */
- /* NOTE: context's lifetime in param is not related to Parser*/
- fn parse_context(context: Context) -> Result<(), &str> {
- /*
- Parser's > &contexts > &str has lifetime of Parser not more
- parse_context > context has lifetime of parse_context
- creating lifetime overlaping confusion
- */
- Parser { context: &context }.parse()
- }
- fn main(){}
- /*
- Parser has reference of Context > Context has a reference of string slice, Contexts lifetime is same as Parser, the string slice in Context consumes the lifetime provided. so in line 9,
- Parser has a lifetime 'a . parse method of Parser returns a Result
- which has &str return type implicitly having the same lifetime
- of Parser.
- line 15, takes a context as param, here the context is moved value,
- the return type is a Result, which has &str that implicitly have
- the same lifetime of parse_context.
- line 19 calling parse() which return a Result<(), &str>, but problem
- is the returned value &str from &context in parse() has the lifetime of Parser, not the Parse_context.
- It is confusing, and very easy to overlook. The explanation is:
- Parser has a lifetime, Parser has a &context, contexts has &str.
- Parser.context and Parser.context(&str value) has lifetime of Parser 'a .
- "Parser's lifetime" != "parse_context lifetime".
- contexts is going out of scope at the end of parse_context. So
- Parser's context should live longer than parse_context's context
- */
Add Comment
Please, Sign In to add comment