009 Rust死靈書之高階trait邊界

linghuyichong發表於2021-02-17

本系列錄製的影片主要放在B站上Rust死靈書學習影片

Rust相關的原始碼資料在:github.com/anonymousGiga

考慮程式碼:

struct Closure<F> {
    data: (u8, u16),
    func: F,
}

impl<F> Closure<F>
    where F: Fn(&(u8, u16)) -> &u8,
{
    fn call(&self) -> &u8 {
        (self.func)(&self.data)
    }
}

fn do_it(data: &(u8, u16)) -> &u8 { &data.0 }

fn main() {
    let clo = Closure { data: (0, 1), func: do_it };
    println!("{}", clo.call());
}

如果要加上生命週期怎麼辦?如下:

struct Closure<F> {
    data: (u8, u16),
    func: F,
}

impl<F> Closure<F>
    where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8,
{
    fn call<'a>(&'a self) -> &'a u8 {
        (self.func)(&self.data)
    }
}

fn do_it<'b>(data: &'b (u8, u16)) -> &'b u8 { &data.0 }

fn main() {
    //'x: 
    {
        let clo = Closure { data: (0, 1), func: do_it };
        println!("{}", clo.call());
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章