への参照を含む構造体の寿命を推測することはできません:は、私は私のコードのコンパイルのこの単純化と自己完結型のバージョンにしようとしています閉鎖
struct FragMsgReceiver<'a, 'b: 'a> {
recv_dgram: &'a mut FnMut(&mut [u8]) -> Result<&'b mut [u8],()>,
}
impl<'a, 'b> FragMsgReceiver<'a, 'b> {
fn new(
recv_dgram: &'a mut FnMut(&mut [u8])
-> Result<&'b mut [u8],()>
) -> Self {
FragMsgReceiver { recv_dgram }
}
}
fn main() {
let recv_dgram = |buff: &mut [u8]| Ok(buff);
let fmr = FragMsgReceiver::new(&mut recv_dgram);
}
ここを誤りである:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:15:43
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 15:22...
--> src/main.rs:15:22
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that expression is assignable (expected &mut [u8], found &mut [u8])
--> src/main.rs:15:43
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^
note: but, the lifetime must be valid for the block suffix following statement 1 at 16:53...
--> src/main.rs:16:53
|
16 | let fmr = FragMsgReceiver::new(&mut recv_dgram);
| _____________________________________________________^
17 | | }
| |_^
note: ...so that variable is valid at time of its declaration
--> src/main.rs:16:9
|
16 | let fmr = FragMsgReceiver::new(&mut recv_dgram);
| ^^^
エラーメッセージからわかるように、コンパイラはbuff
の参照(引数はrecv_dgram
)が実際にrecv_dgram
の内部の本体より長く存続することを理解していません。私は間違っている可能性があります。
いくつかのコンテキストを与えるために、私はRust Tokio UDPソケットをラップする構造体を作成しようとしています。これを行うために、私は関数recv_dgram
への参照を取る。私の元のコードでは、この関数は引数としてバッファをとり、Future
を返します。 Future
が準備完了状態になると、バッファがいっぱいになります。 Future
の項目には、送信者のアドレスとバッファに書き込まれたバイト数も含まれています。
これは機能ではありません。それは閉鎖です。ジェネリックを使うのではなく、特性オブジェクトへの参照が必要な理由はありますか? – Shepmaster
クロージャ引数に型指定子をドロップして、推論を有効にしてから、クロージャに渡す値が結果と同じ寿命になるように指定してから、 'mut'修飾子を修正します。 [完了例](https://play.rust-lang.org/?gist=5650836c790a4394e853ebc76bb84148&version=stable)。 – Shepmaster
@Shepmaster:ありがとう!私は解決できないことがまだあります:recv_dgramはさまざまなバッファを取得し、私の意見ではその寿命は 'a'に関係すべきではないので、 'aはより長く使える'ようにします。私が 'b:'を削除しようとすると、コンパイルエラーが発生します。 '' '&' a mut型:: ops :: FnMut(& 'b mut [u8]) - >&' b mut [u8] + 'a、参照はそれが参照するデータよりも寿命が長い''。どのようにこれを解決することができますか? – real