Is it just me or is Pathbuf's set_file_name and with_file_name seem slightly misleading?

Consider the snippet:

use std::path::PathBuf; 

fn main() {
    let to_folder = PathBuf::from("/tmp/test_assets/"); 
    let to_test_file =  to_folder.with_file_name("test1.txt"); 
    println!("{:?}", to_test_file); 
    // Prints out /tmp/test1.txt where /tmp/test_assets/test1.txt imo is to be expected

The only reason this would make sense to me is if everything is being treated as file, which yes I know as far as the OS concerned everything is a file so it does make sense using that train of thought, but in my opinion it just seems misleading.

I guess my question is what was the rationale behind this choice as suppose to checking if the last char is "/" which suggests the user want to push the file onto the path or if "/" is not there then replace the last part of the path vs always replacing the last part of the path.


The with_* and set_* functions change the last existing component. If you want to add a new component, use join.

I understand the behavior and I am aware that the solution to this problem is join. I am just trying to understand the why because in my head especially when the docs says "Creates an owned PathBuf like self but with the given file name." it seems misleading in my opinion for it to only alter the last component of the path.

Yeh I ran into this too a little while ago and thought it was a bit odd, but does keep it consistent with other methods on PathBuf.

I don't personally see it as a serious issue, but maybe those docs could have an example for set_file_name that demonstrates that the 'file' is the last named part of the path, it doesn't know about directories on your machine.

1 Like