面试题答案
一键面试Future trait的作用
在Rust异步编程中,Future
trait是用于表示一个异步计算的抽象。它代表一个可能尚未完成的计算,并且可以在将来的某个时间点产生一个值(或错误)。Future
trait定义了poll
方法,该方法由Executor
调用,用于尝试推进异步计算。
创建一个简单的Future
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct MyFuture {
completed: bool,
}
impl Future for MyFuture {
type Output = i32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<i32> {
if self.completed {
Poll::Ready(42)
} else {
Poll::Pending
}
}
}
可以这样使用它:
async fn use_my_future() {
let future = MyFuture { completed: true };
let result = future.await;
println!("Result: {}", result);
}
在异步函数中使用Future处理TCP连接建立
首先需要引入tokio
库,它是Rust中常用的异步运行时。
use tokio::net::TcpStream;
async fn connect_to_server() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;
println!("Connected to server!");
Ok(())
}
在上述代码中,TcpStream::connect
返回一个Future
,通过.await
关键字,异步函数会暂停执行,直到这个Future
完成(即连接建立成功或失败),然后继续执行后续代码。