Search code examples
rustaudioerror-handlingiteration

Why is looping through a Devices object not returning Device objects?


I'm trying to Rust's cpal crate to enumerate a system's default host audio devices with the following code:

use cpal::traits::{HostTrait, DeviceTrait};
use cpal::{Device, Host};

fn main(){
    let default_host:Host = cpal::default_host();
    for device in default_host.devices().into_iter(){
        println!("> {}", device.name())
    }
}

When I run the code it becomes apparent that the objects I'm iterating through aren't Device objects but Devices objects, returning the following error:

error[E0599]: no method named `name` found for struct `Devices` in the current scope

   |
16 |         println!("> {}", device.name())
   |                                 ^^^^ method not found in `Devices`

Not sure where to go from here, I've read the relevant cpal and rust documentation repeatedly but I think I'm missing something very fundamental. Any idea what that might be?


Solution

  • Not sure where to go from here, I've read the relevant cpal and rust documentation repeatedly but I think I'm missing something very fundamental. Any idea what that might be?

    HostTrait::Devices can apparently fail so it returns a

    Result<Self::Devices, DevicesError>
    

    Results, like options, are iterable, when iterated they behave as a sequence of 0 (Err) or 1 (Ok) items. That is what your into_iter() invokes, it iterates the result, rather than the devices inside the result.