How do I create a struct instance with two Paths of which one is an extension of another?

Using &Path

Using Path instead of &Path

I'm trying to do this with a struct containing two Paths, actually three, but you get the gist.
Since I want to use these paths in functions that call commands and PathBufs are mutable,
I figured that I would need Paths and not PathBufs, since these paths aren't going to change after the struct has been initialized.

[edit #1]

  • Added second playground using Path instead of &Path
  • Added CommandAction struct to playground to make clear what I use the Paths for.

You are not trying to create a struct with three Paths.

You are creating struct with three references to Path that someone else owns.

Tell us who that someone else and we may go from there.

P.S. If you really need three Paths then you don't need references, fields should of type Path, not & Path.

We need to know what that even is before we may determine if there are smarter way to do that or not.

You are creating data structure which doesn't own three Path segments but referes to segments that someone else owns.

Why? What's the end goal? What are you trying to achieve?

1 Like

This can't possibly work with references. You want this.

Ps.: don't use Path::as_str().unwrap(). This is what .display() is for.

1 Like

Why wouldn't it work with references?

Do I want to use both Path and PathBuf in a struct where the fields are going to be used in method parameters of another struct?

A reference refers to data owned by someone else, and that's "alive" for at least as long as the reference is alive. Since you're creating boot_partition and root_partition from the input data, something needs to ensure that they stay alive for at least as long as the reference is alive.

In a language with a garbage collector, the language can take responsibility for this; it doesn't free the thing the references refer to until the references go away. But Rust has deterministic deallocation instead, so it's on you to find somewhere for the underlying thing to live that's guaranteed to last long enough.

In practice, therefore, this means that the difference between Path and PathBuf is not about mutability, but about ownership; PathBuf owns the storage for the contained path, and thus it guarantees it lasts long enough, while Path is used to refer to storage that someone else owns.

1 Like

Because the method itself creates the paths, so the allocation exists only for the scope of the method body (at most). Returning a reference to that would be wrong (cause UaF/dangling references), so Rust's borrowcheck won't ever allow that.

If you want to create a newly-allocated path based on some computation (that's not just a sub-slice of another path), then you have no choice but to return the owned object.

2 Likes

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.