Here is a snippet of code that works using async_std:
use async_std::{
fs::File,
io::{BufReader, Result},
prelude::*,
};
async fn sum_file_async(file_path: &str) -> Result<f64> {
let f = File::open(file_path).await?;
let reader = BufReader::new(f);
let mut sum = 0.0;
let mut stream = reader.lines(); // KEY POINT!
while let Some(Ok(line)) = stream.next().await {
if let Ok(n) = line.parse::<f64>() {
println!("{}", n);
sum += n;
}
}
Ok(sum)
}
I want to do the same thing with tokio. Here's what I tried:
use std::{io::Result, prelude::*};
use tokio::{
fs::File,
io::{AsyncBufRead, BufReader},
};
async fn sum_file_async(file_path: &str) -> Result<f64> {
let f = File::open(file_path).await?;
let reader = BufReader::new(f);
let mut sum = 0.0;
// Error on next line is:
// method not found in `tokio::io::BufReader<tokio::fs::File>`
let mut stream = reader.lines(); // KEY POINT!
while let Some(Ok(line)) = stream.next().await {
if let Ok(n) = line.parse::<f64>() {
println!("{}", n);
sum += n;
}
}
Ok(sum)
}
The tokio docs mention a lines
method on tokio::io::AsyncBufReadExt
here:
https://docs.rs/tokio/1.2.0/tokio/io/struct.Lines.html
But it's not clear to me from the docs how to create one of those and whether that is an alternative to tokio::io::BufReader
.