Into<PathBuf> - associated type `Output` not found

New to Rust and I am testing accepting a parameter as PathBuf or String.

fn main() {
    let _string_path = "/test/file.rs";
    let _buff_path = std::path::PathBuf::from("/test/file.rs");

    print_file_from_pathbuf(_buff_path);
    print_file_from_string(_string_path);
}
// Compiles 
fn print_file_from_pathbuf(p: std::path::PathBuf) {
    println!("File => {:?}", p.file_name());
}
// error[E0220]: associated type `Output` not found for `std::convert::Into<(std::path::PathBuf,)>`
fn print_file_from_string(p: dyn Into(std::path::PathBuf)) {
    println!("File => {:?}", p.file_name());
}

Read this comment on reddit:

For arguments (advanced): In public interfaces, you usually don't want to use Path or PathBuf directly, but rather a generic P: AsRef<Path> or P: Into<PathBuf> . That way the caller can pass in Path , PathBuf , &str or String .

But i cannot seem to compile some sort of P: Into<PathBuf>.

The compiler seem to point me to that PathBuf is missing Output type. But to me it seems like im clearifying that with saying Into<PathBuf>?

I think there are many things i dont understand here, was wondering if someone could shed some light on this?

You need to write it with generics:

use std::path::PathBuf;

fn print_file_from_string<P: Into<PathBuf>>(p: P) {
    let path = p.into();
    println!("File => {:?}", path.file_name());
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.