简体   繁体   中英

How can I return a gpio_cdev::Error in Rust?

I'm writing a library in Rust using the gpio_cdev crate. I have a struct, and one of its functions looks like this:

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

This works fine. Now I want to add validation to the input pin, so that it's not out-of-range. I know this isn't strictly necessary, and that an invalid pin will get caught by chip.get_line() , but this gives a friendlier error message, and can even allow me to place artificial limits on usable pins (ex: if pins above 20 can technically be used, but I know they should never be used by this function).

My code now looks like this:

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)?;
    ...
}

I would think something like that would work, but gpio_cdev::Error doesn't have a new method, or any other way I can figure out to create an instance of it. Is there a way to do this? Or am I doing something fundamentally wrong? Is this struct only meant to be used internally, within the gpio_cdev crate, without any way to create instances from outside the crate?

gpio_cdev::Error implements From<std::io::Error >

so gpio_cdev::Error can be created using std::io::Error using 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)?;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM