Skip to content

Book: Tasks example out of date #97

Closed
@jlgerber

Description

@jlgerber

Here is the tasks example:

use async_std::fs::File;
use async_std::task;

async fn read_file(path: &str) -> Result<String, io::Error> {
    let mut file = File::open(path).await?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).await?;
    contents
}

fn main() {
    let reader_task = task::spawn(async {
        let result = read_file("data.csv").await;
        match result {
            Ok(s) => println!("{}", s),
            Err(e) => println!("Error reading file: {:?}", e)
        }
    });
    println!("Started task!");
    task::block_on(reader_task);
    println!("Stopped task!");
}

But it does not work. File does not have a read_to_string method seemingly.

Here is what I had to do to get it to work:


async fn read_file(path: &str) -> io::Result<String> {
    //let mut file = File::open(path).await?;
    fs::read_to_string(path).await
}

fn main() {
    let reader_task = task::spawn(async {
        let result = read_file("data.csv").await;
        match result {
            Ok(s) => println!("{}", s),
            Err(e) => println!("Error reading file: {:?}", e),
        }
    });
    println!("Started task!");
    task::block_on(reader_task);
    println!("Stopped task!");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions