如何正确使用Option :: ok_or()方法? [英] How do I use the Option::ok_or() method correctly?

查看:337
本文介绍了如何正确使用Option :: ok_or()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何使用问号运算符在Rust中进行错误处理。我有以下代码:

I'm trying to understand how to use the question mark operator for error handling in Rust. I have this code:

fn main() -> Result<(), &'static str> {
    let foo: i32 = Some("1")
        .ok_or(Err("error 1"))?
        .parse()
        .or(Err("error 2"))?;
    Ok(())
}

此代码无法编译某些原因:

This code can not be compiled for some reason:

error[E0277]: the trait bound `&str: std::convert::From<std::result::Result<_, &str>>` is not satisfied
 --> src/main.rs:2:20
  |
2 |       let foo: i32 = Some("1")
  |  ____________________^
3 | |         .ok_or(Err("error 1"))?
  | |_______________________________^ the trait `std::convert::From<std::result::Result<_, &str>>` is not implemented for `&str`
  |
  = note: required by `std::convert::From::from`

Rust本书有一个示例问号运算符的用法:

The Rust book has an example usage of the question mark operator:

use std::io;
use std::io::Read;
use std::fs::File;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut s = String::new();

    File::open("hello.txt")?.read_to_string(&mut s)?;

    Ok(s)
}

在我看来,它在处理错误方面与我的示例没有太大区别。我看不到代码无效的原因。如果应该为各种 Result 实现 From 特性,为什么Rust本书中的代码可以正常工作? / p>

In my opinion, it doesn't differ much from my example in sense of handling errors. I cannot see a reason for my code to be invalid. If the From trait should be implemented for all kinds of Result why does the code from the Rust book work fine?

推荐答案

ok_or 接受 E ,而不是完整的 Result< T,E> (因为它没有如果通过 Ok 可以做什么)。只需直接传递错误字符串即可:

Unlike or, ok_or takes an E, not a full Result<T, E> (because it wouldn't have anything to do if passed an Ok). Just pass the error string directly:

fn main() -> Result<(), &'static str> {
   let foo: i32 = Some("1")
       .ok_or("error 1")?
       .parse()
       .or(Err("error 2"))?;
    Ok(())
}

错误消息提及 From 特性是因为隐式使用 From 来转换表达式的错误类型转换为返回值的错误类型。如果可行, .ok_or(Err(错误1))将返回 Result<&'static str,Result< _的值,&'static str>> _ 几乎是任何东西,因为 Err (未指定)。 运算符尝试找到 From 的实现,该实现将转换 Result< _和& ;'static str> (表达式的错误类型)转换为&'static str (返回值的错误类型)。由于不存在这样的 From 实现,因此编译器会发出错误。

The reason the error message mentions the From trait is because ? implicitly uses From to convert the expression's error type into the return value's error type. If it worked, .ok_or(Err("error 1")) would return a value of Result<&'static str, Result<_, &'static str>> (_ could be almost anything, since Err doesn't specify). The ? operator attempts to find an implementation of From that would convert Result<_, &'static str> (the expression's error type) into &'static str (the return value's error type). Since no such From implementation exists, the compiler emits an error.

这篇关于如何正确使用Option :: ok_or()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆