Why does the lifetime name appear as part of the function type?

前端 未结 3 1698
遥遥无期
遥遥无期 2021-01-31 19:34

I believe that this function declaration tells Rust that the lifetime of the function\'s output is the same as the lifetime of it\'s s parameter:

fn         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-31 20:08

    The <'a> annotation just declares the lifetimes used in the function, exactly like generic parameters .

    fn subslice<'a, T>(s: &'a [T], until: u32) -> &'a [T] { \\'
        &s[..until as usize]
    }
    

    Note that in your example, all lifetimes can be inferred.

    fn subslice(s: &[T], until: u32) -> &[T] {
        &s[..until as usize]
    }
    
    fn substr(s: &str, until: u32) -> &str {
        &s[..until as usize]
    }
    

    playpen example

提交回复
热议问题