簡體   English   中英

方法返回迭代器的生命周期錯誤

[英]Lifetime error for method returning iterator

在嘗試按照簡單的 XOR 加密 Rust 代碼進行編譯時,我遇到了一個奇怪的生命周期編譯錯誤。

pub struct Encrypt<'a> {
    key:&'a[u8],
    current_index: usize,
}

impl<'a> Encrypt<'a> {
    pub fn new<T: ?Sized + AsRef<[u8]>>(key: &'a T) -> Encrypt<'a> {
        Encrypt { key: key.as_ref(), current_index: 0 }
    }

    pub fn encrypt<T, U>(&'a mut self, data: T) -> impl Iterator<Item = u8>
                where T: IntoIterator<Item = U>, U: std::borrow::Borrow<u8> {
        let iter = data.into_iter().map(|b| {
            let val = b.borrow() ^ self.key[self.current_index];
            self.current_index = (self.current_index + 1) % self.key.len();
            val
        });
        iter
    }
}

我收到以下 bompilation 錯誤:

error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
8  | impl<'a> Encrypt<'a> {
   |      -- hidden type `Map<<T as IntoIterator>::IntoIter, [closure@src/lib.rs:36:41: 40:10]>` captures the lifetime `'a` as defined here
...
41 |         iter

這真的很奇怪,因為方法 encrypt() 不返回任何引用,但編譯器似乎仍然將 self 的生命周期與它相關聯。 請為這個問題提出一個解決方案。 提前致謝!

這是一個常見問題,可能由不正確的生命周期注釋引起。 問題是您將返回的迭代器的生命周期綁定到self的生命周期,即'a 但是你不關心self的生命周期,你只關心你借用它的引用的生命周期, &mut self ,我們稱之為生命周期's

現在我們只需要告訴編譯器:

impl<'a> Encrypt<'a> {
    pub fn encrypt<'s, T, U>(&'s mut self, data: T) -> impl Iterator<Item = u8> + 's
    //             ^^         ^^                                                ^^^^
    // tie the return value's lifetime to the lifetime for which we burrow `self` 
    // instead of the whole lifetime of `self`.
    where
        T: IntoIterator<Item = U> + 's,
        //                        ^^^^
        // That'll transitively require this bound
        U: std::borrow::Borrow<u8>,
    {
        let iter = data.into_iter().map(|b| {
            let val = b.borrow() ^ self.key[self.current_index];
            self.current_index = (self.current_index + 1) % self.key.len();
            val
        });
        iter
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM