以下Rust代码编译并运行没有任何问题.
fn main() {
let text = "abc";
println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)
在那之后,我尝试了类似的东西....但它没有编译
fn main() {
let text = "word1 word2 word3";
println!("{}", to_words(text).take(2).count());
}
fn to_words(text: &str) -> &Iterator<Item = &str> {
&(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)
主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:
error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
--> src/main.rs:3:43
|
3 | println!("{}", to_words(text).take(2).count());
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
`std::iter::Iterator<Item=&str> : std::marker::Sized`
`std::iter::Take<std::iter::Iterator<Item=&str>> …Run Code Online (Sandbox Code Playgroud) 我正在尝试根据Option函数的输入切换行为.想法是基于给定Option是否存在来迭代.这是一个最小的,如果愚蠢的例子:
use std::iter;
fn main() {
let x: Option<i64> = None;
// Repeat x 5 times if present, otherwise count from 1 to 5
for i in match x {
None => 1..5,
Some(x) => iter::repeat(x).take(5),
} {
println!("{}", i);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
error[E0308]: match arms have incompatible types
--> src/main.rs:7:14
|
7 | for i in match x {
| ______________^
8 | | None => 1..5,
9 | | Some(x) => iter::repeat(x).take(5),
| | …Run Code Online (Sandbox Code Playgroud) 鉴于此定义foo:
let foo = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
Run Code Online (Sandbox Code Playgroud)
我希望能够编写这样的代码:
let result: Vec<_> = foo.iter()
.enumerate()
.flat_map(|(i, row)| if i % 2 == 0 {
row.iter().map(|x| x * 2)
} else {
std::iter::empty()
})
.collect();
Run Code Online (Sandbox Code Playgroud)
但是这引发了关于if和else子句具有不兼容类型的错误.我尝试map暂时删除,我尝试在闭包外定义一个空向量,然后返回迭代器,如下所示:
let empty = vec![];
let result: Vec<_> = foo.iter()
.enumerate()
.flat_map(|(i, row)| if i % 2 == 0 {
row.iter() //.map(|x| x * 2)
} else {
empty.iter()
})
.collect();
Run Code Online (Sandbox Code Playgroud)
这似乎有点傻,但它编译.如果我试图取消注释map然后它仍然抱怨if和else子句具有不兼容的类型.以下是错误消息的一部分:
error[E0308]: if and …Run Code Online (Sandbox Code Playgroud) 我想构建一个收集天气更新并将它们表示为流的程序。我想get_weather()在一个无限循环中调用,在finish和start之间有 60 秒的延迟。
简化版本如下所示:
async fn get_weather() -> Weather { /* ... */ }
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
loop {
tokio::timer::delay_for(std::time::Duration::from_secs(60)).await;
let weather = get_weather().await;
yield weather; // This is not supported
// Note: waiting for get_weather() stops the timer and avoids overflows.
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法轻松做到这一点?
超过 60 秒tokio::timer::Interval时使用将不起作用get_weather():
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
tokio::timer::Interval::new_with_delay(std::time::Duration::from_secs(60))
.then(|| get_weather())
}
Run Code Online (Sandbox Code Playgroud)
如果发生这种情况,下一个功能将立即启动。我想在上一次get_weather()开始和下一次get_weather()开始之间保持 …