我正在使用gpio_cdev
条板箱在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()
捕获,但这会给出更友好的错误消息,甚至可以允许我对可用引脚进行人为限制(例如:如果技术上大于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
crate 内部使用,而无从 crate 外部创建实例的方式?
最佳答案
gpio_cdev::Error实现From<std::io::Error>
所以可以使用into()使用std::io::Error创建gpio_cdev::Error
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)?;
...
}
关于rust - 如何在Rust中返回gpio_cdev::Error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66602956/