What are the Rust types denoted with a single apostrophe?

后端 未结 2 1481
北海茫月
北海茫月 2021-01-30 10:18

I\'ve encountered a number of types in Rust denoted with a single apostrophe:

\'static
\'r
\'a

What is the significance of that apostrophe? May

2条回答
  •  生来不讨喜
    2021-01-30 10:45

    To add to quux00's excellent answer, named lifetimes are also used to indicate the origin of a returned borrowed variable to the rust compiler.

    This function

    pub fn f(a: &str, b: &str) -> &str {
      b
    }
    

    won't compile because it returns a borrowed value but does not specify whether it borrowed it from a or b.

    To fix that, you'd declare a named lifetime and use the same lifetime for b and the return type:

    pub fn f<'r>(a: &str, b: &'r str) -> &'r str {
    //      ----              ---         ---
      b
    }
    

    and use it as expected

    f("a", "b")
    

提交回复
热议问题