我正在使用DHT11 library,其中基于esp32 implementation的参数gpio对于new必须实现InputPinOutputPin. 所以我创建了一个函数,它返回这两个特征中的一个超级特征的TraitObject.但当我想取消对它的引用以实际调用new时,我得到了错误doesn't have a size known at compile-time.

这是我从以上提到的trait 中得出的超级trait :

trait InputOutputPin: InputPin<Error = EspError> + OutputPin<Error = EspError> {}
impl<T: InputPin<Error = EspError> + OutputPin<Error = EspError>> InputOutputPin for T {}

这是根据给定的管脚编号创建GPIO的函数:

    fn get_gpio(pin: &u8) -> Result<&dyn InputOutputPin, &'static str>{
        match pin {
            33 => Ok(&Peripherals::take().unwrap().pins.gpio33.into_input_output().unwrap()),
            32 => Ok(&Peripherals::take().unwrap().pins.gpio32.into_input_output().unwrap()),
            27 => Ok(&Peripherals::take().unwrap().pins.gpio27.into_input_output().unwrap()),
            26 => Ok(&Peripherals::take().unwrap().pins.gpio26.into_input_output().unwrap()),
            25 => Ok(&Peripherals::take().unwrap().pins.gpio25.into_input_output().unwrap()),
            _ => Err("Pin not configurable for dht")
        }
    }

下面是函数结果的赋值方式:

let gpio = Self::get_gpio(pin).unwrap();
let dht = Dht11::new(*gpio);

我所要做的就是根据所 Select 的管脚编号创建一个DHT11对象,但是the esp32 library通过使用makro将每个GPIO实现为其自己的 struct . 我错过了什么,或者有没有一个明显的、更好的方法来做到这一点.

推荐答案

ESP32 HAL对GPIO引脚有一个degrade的方法,它消除了引脚特定的类型,所以你不需要使用你的Dyn超级特性.

修改后的代码更像这样:

fn get_gpio(pin: &u8) -> Result<GpioPin<InputOutput>, &'static str>{
        match pin {
            33 => Ok(&Peripherals::take().unwrap().pins.gpio33.into_input_output().unwrap().degrade()),
            32 => Ok(&Peripherals::take().unwrap().pins.gpio32.into_input_output().unwrap().degrade()),
            27 => Ok(&Peripherals::take().unwrap().pins.gpio27.into_input_output().unwrap().degrade()),
            26 => Ok(&Peripherals::take().unwrap().pins.gpio26.into_input_output().unwrap().degrade()),
            25 => Ok(&Peripherals::take().unwrap().pins.gpio25.into_input_output().unwrap().degrade()),
            _ => Err("Pin not configurable for dht")
        }
    }

Rust相关问答推荐

如何在Rust中为具有多个数据持有者的enum变体编写文档 comments ?

将此字符串转换为由空格字符分隔的空格

将JSON密钥转换为Polars DataFrame

我怎样才能从一个Rust 的日期中go 掉3年?

如何创建引用构造函数拥有的变量的对象?

当rust中不存在文件或目录时,std::FS::File::Create().unwire()会抛出错误

为什么std repeat trait绑定在impl块和关联函数之间?

RUST应用程序正在退出,错误代码为:(退出代码:0xc0000005,STATUS_ACCESS_VIOLATION)

在本例中,为什么我不能一次多次borrow 可变变量?

正则表达式中的重叠匹配?(铁 rust 正则式发动机)

习语选项<;T>;到选项<;U>;当T->;U用From定义

Rust Option 的空显式泛型参数

Rust 文件未编译到 dll 中

按下 Ctrl + C 时优雅地停止命令并退出进程

具有在宏扩展中指定的生命周期的枚举变体数据类型

如何连接 Rust 中的相邻切片

如何获取函数中borrow 的切片的第一部分?

将 (T, ()) 转换为 T 安全吗?

使用 rust-sqlx/tokio 时如何取消长时间运行的查询

为什么 std::iter::Peekable::peek 可变地borrow self 参数?