面试题答案
一键面试-
在Rust异步函数中使用
?
操作符处理异步操作错误:- 在Rust中,
?
操作符可以在异步函数中用于处理Result
类型的返回值。当异步操作返回Err
时,?
操作符会提前返回,将错误值从当前异步函数中传播出去。 - 例如,考虑使用
tokio::fs::read_to_string
读取文件内容的异步操作,该函数返回Result<String, io::Error>
。在异步函数中可以这样使用?
操作符:
use tokio::fs; async fn read_file() -> Result<String, std::io::Error> { let content = fs::read_to_string("example.txt").await?; Ok(content) }
- 在上述代码中,如果
fs::read_to_string
操作返回Err
,?
操作符会将这个io::Error
从read_file
函数中传播出去,提前结束函数执行。
- 在Rust中,
-
在异步函数链中传递和处理错误:
- 可以将多个异步函数连接起来,并且在这个过程中使用
?
操作符传递和处理错误。 - 例如,假设有两个异步函数,一个读取文件,另一个解析文件内容(假设解析也可能出错):
use tokio::fs; async fn read_file() -> Result<String, std::io::Error> { let content = fs::read_to_string("example.txt").await?; Ok(content) } fn parse_content(content: String) -> Result<u32, &'static str> { content.parse().map_err(|_| "Failed to parse") } async fn process_file() -> Result<u32, Box<dyn std::error::Error>> { let content = read_file().await?; let result = parse_content(content)?; Ok(result) }
- 在
process_file
函数中,首先调用read_file
异步函数读取文件内容,如果read_file
返回错误,?
操作符会将错误传播出去。如果读取成功,再调用parse_content
函数解析内容,若解析出错,同样?
操作符会将错误传播出去。最终process_file
函数会将所有可能的错误包装成Box<dyn std::error::Error>
类型进行返回,这样上层调用者可以统一处理这些错误。
- 可以将多个异步函数连接起来,并且在这个过程中使用