Kyle
Kyle

Reputation: 793

Iterate over vector of structs in Rust

I'm trying to debug why my device isn't being recognized on my MacOS BigSur laptop in Rust. I've ran my Python code to verify that it exists, though it's unable to be read to which is very strange. As Rust has the serial port library and it seems a lot more robust than PyUSB I decided to use it.

The code I'm using is taken from a pre-existing project that worked on x86_64 processors, Big Sur using Apples M1 chip.

Here's the code:

#[cfg(not(feature = "fake_serial"))]
pub fn start_serial_probe(
    custom_tty: &Option<String>,
// ) -> Result<crossbeam_channel::Receiver<B0xxMessage>, ViewerError> {
) {
    let b0xx_port = serialport::available_ports();
    for port in &b0xx_port {
        // let port : serialport::SerialPortInfo = port;
        println!("{} ", port.port_name);
    }
    ...

The error when compiling is the same as what I'm receiving in VSCode.

no field port_name on type &std::vec::Vec<serialport::SerialPortInfo>

I'm not entirely sure how to grab the items through the vector, as most use integers, etc in some type of array.

Thanks!

Upvotes: 0

Views: 662

Answers (1)

Peter Hall
Peter Hall

Reputation: 58695

The function serialport::available_ports() returns a Result<Vec<SerialialPortInfo>>, not a Vec<SerialPortInfo>.

The confusion here is likely because Result implements IntoIterator, and looping over it will yield either one or zero elements depending on if it is Ok or Err respectively. The item is a Vec in this case, which is why you can't access fields of SerialialPortInfo.

This should work:

if let Ok(b0xx_port) = serialport::available_ports() {
    for port in &b0xx_port {
        println!("{} ", port.port_name);
    }
} else {
    // handle the error
}

Upvotes: 3

Related Questions