Structs, Lifetimes and confusion


#1

Let me bombard you with the code first.

use std::env;
use std::path::Path;

struct MyStruct {
    // This obviously needs a lifetime but I'm not sure what it'll be... 
    // I'm thinking same as a MyStruct object... If so, how do I say that?
    pub path: &Path
}

impl MyStruct {
    fn new() -> MyStruct {
        let my_path = MyStruct::compute_path();
        MyStruct { path: my_path }
    }

    fn compute_path() -> Path {
        env::current_exe().unwrap().as_path()
    }
}


fn main() {
    let my_struct = MyStruct::new();

    // I want this to print the location of my executable, i.e. the result of MyStruct::compute_path
    println!("Location: {}", my_struct.path);
}

I realize that my_path goes out of scope and hence I cannot store it in the struct.

My question is, how do I store it (the value of my_path) in my structure? Should I Box it? Is there a non-boxy way of doing this?

I’m a newbie to Rust. So it’s probably true I’m trying something dumb and there’s a better way to do all of this. If so, please guide me. :angel:


#2

Path is the path version of str, so it’s a borrowed slice of an owned path. The owned version (analogous to String) is called PathBuf. You want MyStruct to own the path, so you’ll have to use PathBuf, which, luckily, is the return type of current_exe. The solution to your problem is to remove the call to as_path and change the type of path to PathBuf.


#3

Ooh… So, it’s a borrowed slice. That’s why… It all makes sense now.

Thanks @ogeon!


#4

You can actually guess it from the method name. as_* is usually a cheap conversion and will often result in a reference of some kind. into_*, on the other hand, is usually allowed to be more expensive and will often result in an owned value.


#5

That’s a nice thing to know…

Any more such examples of information about operations that can be guessed?


#6

There are a few conventions like these, and I think most of them are covered under section 2.4 in this (incomplete) style guide: https://aturon.github.io/ I’d recommend reading through it to get a grasp of the general style and conventions. There are, of course, variations throughout the ecosystem, but that one should be based on how things are done in the standard libraries.