Guest User

Untitled

a guest
Nov 15th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. /* the tuple is a reference, which has lifetime till Context */
  2. struct Context<'b>(&'b str);
  3.  
  4. /* Parser's context is reference, which is a type of Context */
  5. /* (reference to context), and (reference to str_slice in context)
  6. has has same lifetime of 'a
  7. */
  8. struct Parser<'a> {
  9. context: &'a Context<'a>,
  10. }
  11.  
  12. impl<'a> Parser<'a> {
  13. fn parse(&self) -> Result<(), &str> {
  14. Err(&self.context.0[1..])
  15. }
  16. }
  17. /* check the param, parse_context takes ownership of Context */
  18. /* NOTE: context's lifetime in param is not related to Parser*/
  19. fn parse_context(context: Context) -> Result<(), &str> {
  20. /*
  21. Parser's > &contexts > &str has lifetime of Parser not more
  22. parse_context > context has lifetime of parse_context
  23. creating lifetime overlaping confusion
  24. */
  25. Parser { context: &context }.parse()
  26. }
  27. fn main(){}
  28.  
  29. /*
  30. 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,
  31. Parser has a lifetime 'a . parse method of Parser returns a Result
  32. which has &str return type implicitly having the same lifetime
  33. of Parser.
  34.  
  35. line 15, takes a context as param, here the context is moved value,
  36. the return type is a Result, which has &str that implicitly have
  37. the same lifetime of parse_context.
  38.  
  39. line 19 calling parse() which return a Result<(), &str>, but problem
  40. is the returned value &str from &context in parse() has the lifetime of Parser, not the Parse_context.
  41. It is confusing, and very easy to overlook. The explanation is:
  42.  
  43. Parser has a lifetime, Parser has a &context, contexts has &str.
  44. Parser.context and Parser.context(&str value) has lifetime of Parser 'a .
  45. "Parser's lifetime" != "parse_context lifetime".
  46. contexts is going out of scope at the end of parse_context. So
  47. Parser's context should live longer than parse_context's context
  48. */
Add Comment
Please, Sign In to add comment