在 Rust 中引用对象

问题描述 投票:0回答:1

我想引用一个在循环外部定义的对象

slow_uart

fn main() -> ! {
    // .....
    // Initializations 
   
    let slow_bdrate = <Rate<u32, 1, 1>>::Hz(120000);
    let slow_uart = UartConfig::new(
        slow_bdrate,
        uart::DataBits::Eight,
        None,
        uart::StopBits::One,
    );

    let data: u8 = 0;
    let uart_peripheral = UartPeripheral::new(pac.UART0, uart_pins, &mut pac.RESETS);

    loop {
        
       uart_peripheral.enable(slow_uart, clocks.peripheral_clock.freq())
            .unwrap();

        uart_peripheral.write_full_blocking(&data);

        delay.delay_ms(100);
    }
}

我是 Rust 新手,但是还有其他方法可以访问循环之外的对象吗?编译器建议使用

Copy()
特征,但似乎没有为此函数实现。我可以使用类似于 C++ 中的指针的方式来引用它吗?这里有哪些好的做法?

我尝试将

uart_peripheral
移动到循环中,但我也必须移动其参数的所有其他实例,但我宁愿不这样做。

非常有帮助

编辑

这是编译器的输出:

error[E0382]: use of moved value: `uart_peripheral`
   --> blinky.rs:131:9
    |
112 |     let mut uart_peripheral = UartPeripheral::new(pac.UART0, uart_pins, &mut pac.RESETS);
    |         -------- move occurs because `uart_peripheral` has type `UartPeripheral<rp2040_hal::uart::Disabled, UART0, (rp2040_hal::gpio::Pin<Gpio0, FunctionUart, PullDown>, rp2040_hal::gpio::Pin<Gpio1, FunctionUart, PullDown>)>`, which does not implement the `Copy` trait
...
126 |     loop {
    |     ---- inside of this loop
...
131 |         uart_peripheral.enable(slow_uart, clocks.peripheral_clock.freq())
    |         ^^^^ value moved here, in previous iteration of loop

error[E0382]: use of moved value: `slow_uart`
   --> blinky.rs:131:21
    |
98  |     let slow_uart = UartConfig::new(
    |         --------- move occurs because `slow_uart` has type `UartConfig`, which does not implement the `Copy` trait
...
126 |     loop {
    |     ---- inside of this loop
...
131 |         uart_peripheral.enable(slow_uart, clocks.peripheral_clock.freq())
    |                     ^^^^^^^^^ value moved here, in previous iteration of loop
object rust embedded rp2040
1个回答
0
投票

由于您发布的代码不可重现,我会回答,但需要注意的是,发布的代码未经测试。所以那里可能还有其他错误。

您面临的问题是

UartPeripheral::enable
函数似乎消耗外围对象并返回一个新的启用对象。这只能完成一次,也只需要一次。

因此,您只需将

enable
移出循环并使用返回的启用对象而不是
write_full_blocking
的原始对象,理论上它应该有效。再次强调,未经测试,因为您的代码不能完全重现。

fn main() -> ! {
    // .....
    // Initializations 
   
    let slow_bdrate = <Rate<u32, 1, 1>>::Hz(120000);
    let slow_uart = UartConfig::new(
        slow_bdrate,
        uart::DataBits::Eight,
        None,
        uart::StopBits::One,
    );

    let data: u8 = 0;
    let uart_peripheral = UartPeripheral::new(pac.UART0, uart_pins, &mut pac.RESETS);

    let enabled_uart_peripheral = uart_peripheral.enable(slow_uart, locks.peripheral_clock.freq()).unwrap();

    loop {
        enabled_uart_peripheral.write_full_blocking(&data);

        delay.delay_ms(100);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.