实现说明
逻辑集中在函数 fetch_remote、main里。
输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。
使用要点
- 依赖检查:
tokio::time::——不是内建的,项目里必须有。 - 演示输出是带标签的(
received、request timed out、first:),每个操作都会留下自己的一行标注。 - 运行整个文件:
main会依次驱动fetch_remote。
常见问题
有第三方依赖吗?
tokio::time::——运行前用包管理器装上。
入口签名:fn fetch_remote() -> String
核心语句
match timeout(Duration::from_millis(50), fetch_remote()).await {
Ok(body) => println!("received {body}"),
Err(_) => println!("request timed out"),
}
async fn fetch_remote() -> String {
sleep(Duration::from_millis(200)).await;
String::from("payload")
}
代码示例
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn fetch_remote() -> String {
sleep(Duration::from_millis(200)).await;
String::from("payload")
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(50), fetch_remote()).await {
Ok(body) => println!("received {body}"),
Err(_) => println!("request timed out"),
}
tokio::select! {
result = fetch_remote() => println!("first: {result}"),
_ = sleep(Duration::from_millis(100)) => println!("deadline hit first"),
}
}