Newbie question - how to get rid of som Some("xxx") if I print sth

Hi,

I am pretty new to Rust and trying to do a few simple things in it to learn it a bit.

My first project is to create a fast dir walker with walkdir::WalkDir.

My code:

	for entry in WalkDir::new(start_dir).into_iter().filter_map(|e| e.ok()) {
	    println!("{} {:?}", entry.path().display(), entry.path().extension());
	}

produces:

.\target\debug\dwalk-dir.exe Some("exe")

How do I get rid of this Some in front of the exe? I guess it should be a simple solution. Please can somebody point me in the right direction?

Some is printed because the return type of the extension method is an Option, indicating that there might not be a return value. You need to handle this case in your code. What would you like to print if the file doesn't have an extension?

1 Like

Thanks for the fast response.

That makes sense. In that case I would like to print an empty string "". How would I do that?

Also just discovered std::option - Rust and I try to understand it. It makes sense.

Try this:

entry.path().extension().map_or("".into(), |ext| ext.to_string_lossy())
//                              ^                ^
//             what to do if None                what to do if Some
1 Like

unwrap_or can also be useful in situations like these! Given the to_string_lossy() bit, I think @jethrogb is right, but if that wasn't needed, it would work too.

1 Like

Thanks it worked. And I also looked up the doc and I guess what happens in that code. :slight_smile:

1 Like