[][src]Function tao_of_rust::ch06::closures::higher_kind_lifetime

pub fn higher_kind_lifetime()

高阶生命周期

Base usage: Error版本

use std::fmt::Debug;
trait DoSomething<T> {
    fn do_sth(&self, value: T);
}
impl<'a, T: Debug> DoSomething<T> for &'a usize {
    fn do_sth(&self, value: T) {
        println!("{:?}", value);
    }
}
fn foo<'a>(b: Box<DoSomething<&'a usize>>) {
    let s: usize = 10;
    b.do_sth(&s) // error[E0597]: `s` does not live long enough
}
fn main(){
    let x  = Box::new(&2usize);
    foo(x);
}Run

Base usage: 使用for<>高阶生命周期语法

use std::fmt::Debug;
trait DoSomething<T> {
    fn do_sth(&self, value: T);
}
impl<'a, T: Debug> DoSomething<T> for &'a usize {
    fn do_sth(&self, value: T) {
        println!("{:?}", value);
    }
}
fn bar(b: Box<for<'f> DoSomething<&'f usize>>) {
    let s: usize = 10;
    b.do_sth(&s);
}
fn main(){
    let x  = Box::new(&2usize);
    bar(x);
}Run

Base usage: 以闭包为结构体字段,自动推断引用的生命周期参数

struct Pick<F> {
    data: (u32, u32),
    func: F,
}
impl<F> Pick<F>
    where F: Fn(&(u32, u32)) -> &u32
    {
    fn call(&self) -> &u32 {
        (self.func)(&self.data)
}
}
fn max(data: &(u32, u32)) -> &u32 {
    if data.0 > data.1{
        &data.0
    }else{
        &data.1
    }

}
fn main() {
   let elm = Pick { data: (3, 1), func: max };
   println!("{}", elm.call());
}Run

Base usage: 以闭包为结构体字段,显式指定引用的生命周期参数

struct Pick<F> {
    data: (u32, u32),
    func: F,
}
impl<F> Pick<F>
    where F: for<'f> Fn(&'f (u32, u32)) -> &'f u32, // 显式指定
    {
    fn call(&self) -> &u32 {
        (self.func)(&self.data)
 }
}
fn max(data: &(u32, u32)) -> &u32 {
    if data.0 > data.1{
        &data.0
    }else{
        &data.1
    }
}
fn main() {
   let elm = Pick { data: (3, 1), func: max };
   println!("{}", elm.call());
}Run