私はRustのライフタイムの基本とiteratorでのイテレータの使い方を理解しましたが、それでもタプルの繰り返しが可能で、ヒープに割り当てられたタプルのiterableを返す関数を定義するのには問題があります。参照のIntoIteratorを取得し、変更された値への参照のボックス化された反復子を返す方法はありますか?
(私は "反復可能" はルーストに何を意味するものではありませんが、私はまだIntoInterator
の代わりに使用することを知っている)
use std::iter::{once, repeat};
fn foo<'a, I>(costs: I) -> Box<Iterator<Item = &'a (i32, f32)>>
where
I: IntoIterator<Item = &'a (usize, f32)>,
{
let preliminary_examination_costs = once(10.0).chain(repeat(20.0));
let id_assignment_costs = once(10.0).chain(repeat(20.0));
let batch_fixed = once(10.0).chain(repeat(0.0));
let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
temp.sort_by_key(|&(_, &(n, cost))| n);
Box::new(temp.into_iter().map(|(i, &(n, cost))| {
(
i,
cost + preliminary_examination_costs.next().unwrap()
+ id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
)
}))
}
ここでエラーです:
error[E0277]: the trait bound `std::vec::Vec<(usize, &(i32, f32))>: std::iter::FromIterator<(usize, &'a (usize, f32))>` is not satisfied
--> src/main.rs:10:73
|
10 | let temp: Vec<(usize, &(i32, f32))> = costs.into_iter().enumerate().collect();
| ^^^^^^^ a collection of type `std::vec::Vec<(usize, &(i32, f32))>` cannot be built from an iterator over elements of type `(usize, &'a (usize, f32))`
|
= help: the trait `std::iter::FromIterator<(usize, &'a (usize, f32))>` is not implemented for `std::vec::Vec<(usize, &(i32, f32))>`
error[E0271]: type mismatch resolving `<[[email protected]/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_] as std::ops::FnOnce<((usize, &(i32, f32)),)>>::Output == &(i32, f32)`
--> src/main.rs:12:5
|
12 |/ Box::new(temp.into_iter().map(|(i, &(n, cost))| {
13 | | (
14 | | i,
15 | | cost + preliminary_examination_costs.next().unwrap()
16 | | + id_assignment_costs.next().unwrap() + batch_fixed.next().unwrap(),
17 | | )
18 | | }))
| |_______^ expected tuple, found &(i32, f32)
|
= note: expected type `(usize, f32)`
found type `&(i32, f32)`
= note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::vec::IntoIter<(usize, &(i32, f32))>, [[email protected]/main.rs:12:35: 18:6 preliminary_examination_costs:_, id_assignment_costs:_, batch_fixed:_]>`
= note: required for the cast to the object type `std::iter::Iterator<Item=&(i32, f32)>`
あなたのコードには、あなたが言及しているようなものより多くの問題があります。 'usize'は暗黙的に' i32'に変換されません。さらに、最後に新しいタプルにマップを実行しているので、返されたiterableのアイテムは、もはや ''a'の生涯にバインドされた参照ではいけません。 –
それを見て、あなたは[this](https://play.rust-lang.org/?gist=f20ffa67c1bc814279b53d0dce351545&version=stable)のようなものを探しています。しかし、あなたの問題に合わせたデバッグセッションがなければ、あなたの質問に対処する方法を見つけることができません。スタックオーバーフローの問題としてはほとんど利益はありません。 –