Rust how to return the file_name if return None thread main panicked Option::unwrap()

191 Views Asked by At

I have this little program which using Walkdir to get the all the mp3 files on the my home dir . i'm using audiotags audiotags to get the metadata of the mp3 file what i want to do is get the metadata and return it via struct but when the create_song_struct is executed the it panicked and thread 'main' panicked at 'called Option::unwrap()' on a 'None' value' i'm new to rust and i don't know how to implement the function

use audiotags::Tag;
#[allow(unused_imports)]
#[allow(non_snake_case)]
use rust_play::audio::playing;
use rust_play::files::get_files;

#[allow(dead_code)]
#[derive(Debug)]
struct Song {
    file_path: String,
    title: String,
    artist: String,
    song_name: String,
}

fn main() {
    let files = get_files::get_mp3_files();

    for file in files {
        println!("{}", file);
        create_song_struct(&file);
    }
}

fn create_song_struct(file_path: &str) {
    let tags = Tag::default().read_from_path(&file_path).unwrap();

    let title = tags.title().unwrap();
    let artist = tags.artist().unwrap();
    let track = tags.track();

    println!("title:{:?}\nartist:{:?}\ntrack:{:?}", title, artist, track);
}
2

There are 2 best solutions below

0
Masklinn On

i'm new to rust and i don't know how to implement the function

Readers don't either, because we've no idea what you're trying to achieve.

unwrap simply means "panic if there is no value". Usually, functions and methods return an Option for a reason e.g. the file does not exist, or the file has no title or artist.

It's up to you how to handle these conditions.

Now since you're on your own machine, and you just got the file name, the first condition is probably OK (in other cases though, the code is sensible to TOCTOU so it's not generally safe).

The other two though, they're just properties of files. So you have to decide how to handle them, whether it's:

  • show their reality
  • replace with a default
  • skip processing / printing the file
  • perform alternate processing
  • ...
0
Jmb On

You should really include the full error, including the file and line number. Since the message mentions Option::unwrap, I'll assume that the error doesn't come from read_from_path (which returns a Result, not an Option), but instead that you have a file without metadata or with only partial metadata. One way to handle this is to replace the unwraps with unwrap_or, which allow you to specify a default value:

fn create_song_struct(file_path:&str) {
   let tags = Tag::default().read_from_path(&file_path).unwrap();

   let title = tags.title().unwrap_or ("unknown title");
   let artist = tags.artist().unwrap_or ("unknown artist");
   let track = tags.track();

   println!("title:{:?}\nartist:{:?}\ntrack:{:?}",title,artist,track);
}