最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - What is the difference between adding the `?` operator and not adding it in this call? - Stack Overflow

programmeradmin7浏览0评论

In this code, what is the difference between adding the ? operator after the call to read_to_string() and not adding it? Why do both work = what happens if this call fails?

fn chaining() -> Result<String, std::io::Error> {
    let mut username = String::new();
    File::open("fake.txt")?.read_to_string(&mut username)?; // <- removing ? here also works
    Ok(username)
}

In this code, what is the difference between adding the ? operator after the call to read_to_string() and not adding it? Why do both work = what happens if this call fails?

fn chaining() -> Result<String, std::io::Error> {
    let mut username = String::new();
    File::open("fake.txt")?.read_to_string(&mut username)?; // <- removing ? here also works
    Ok(username)
}
Share Improve this question asked Nov 18, 2024 at 18:59 evilmandarineevilmandarine 4,5934 gold badges22 silver badges49 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

If you remove the ? operator, errors when reading the file will be silently ignored (although the compiler will warn you). If you keep it, errors will return from the function with Err. So you probably want to keep it.

As for what happens to the String passed if you ignore the error, the documentation of read_to_string() refers to the documentation of read_to_end(), which says the following:

If any other read error is encountered then this function immediately returns. Any bytes which have already been read will be appended to buf.

发布评论

评论列表(0)

  1. 暂无评论