【问题标题】:How can I return a gpio_cdev::Error in Rust?如何在 Rust 中返回 gpio_cdev::Error?
【发布时间】:2021-03-12 15:41:40
【问题描述】:

我正在使用 gpio_cdev crate 在 Rust 中编写一个库。 我有一个结构,它的一个函数如下所示:

pub fn add_channel(&mut self, name: String, pin: u8) -> Result<(), gpio_cdev::Error> {
    let line = self.chip.get_line(pin as u32)?;
    ...
}

这很好用。现在我想向输入引脚添加验证,使其不会超出范围。我知道这不是绝对必要的,chip.get_line() 会捕获无效的 pin,但这会给出更友好的错误消息,甚至可以让我对可用 pin 进行人为限制(例如:如果 pin 超过 20 可以技术上可以使用,但我知道它们不应该被这个函数使用)。

我的代码现在看起来像这样:

pub fn add_channel(&mut self, name: String, pin: u8) -> Result<(), gpio_cdev::Error> {
    if pin > 20 {
        return Err(gpio_cdev::Error::new(format!("Pin {} is out of range!", pin)));
    }

    let line = self.chip.get_line(pin as u32)?;
    ...
}

我认为这样的事情会起作用,但gpio_cdev::Error 没有new 方法,或者我能想出的任何其他方法来创建它的实例。有没有办法做到这一点?还是我做错了什么?这个结构是否只打算在内部使用,在 gpio_cdev 板条箱内,没有任何方法可以从板条箱外部创建实例?

【问题讨论】:

    标签: rust


    【解决方案1】:

    gpio_cdev::Error 实现From<std::io::Error>

    所以 gpio_cdev::Error 可以使用 std::io::Error 使用 into() 来创建

    pub fn add_channel(&mut self, name: String, pin: u8) -> Result<(), gpio_cdev::Error> {
        if pin > 20 {
            let io_err = std::io::Error::new(std::io::ErrorKind::Other, format!("Pin {} is out of range!", pin));
            return Err(io_err.into());
        }
    
        let line = self.chip.get_line(pin as u32)?;
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2020-07-07
      • 1970-01-01
      相关资源
      最近更新 更多