Hi community,
after the Rust book and Rustlings tutorial I started my very first program and as an old OOP programmer an immediate code design question arises to me.
The task is not harder than providing the path to the OS specific data directory to different places within my code. I have chosen the directories crate for that, which has a neat interface for my requirement:
if let Some(proj_dirs) = ProjectDirs::from("com", "Foo Corp", "Bar App") {
proj_dirs.config_dir();
}
So the easiest and most chaotic way seems to create a variable mostly at the start of the code, which holds the returned &Path
and pass that variable around:
let data_dir: &Path = ProjectDirs::from("comm", "foo", "bar")
.expect("No valid home directory path could be retrieved from the operating system.")
.data_dir();
My object oriented brain however tells me, to store and organize this configuration, as well as all future configurations, into a struct, which I create once and use it all over the code. I started with following first try:
use directories::ProjectDirs;
use std::path::Path;
pub struct ProcopConfig {
pub data_dir: &Path,
}
impl ProcopConfig {
pub fn new() -> ProcopConfig {
let data_dir: &Path = ProjectDirs::from("comm", "foo", "bar")
.expect("No valid home directory path could be retrieved from the operating system.")
.data_dir();
ProcopConfig { data_dir }
}
}
Of course, this code has an error, the missing lifetime parameter for the data_dir
fiel within my struct.
However fixing this error - as first time Rust programmer - I just run into more errors:
- Adding the lifetime specifier 'static tells me, that the temporary value of
ProjectDirs[...].data_dir()
is dropped while borrowed. I can't figure out, how to create the&Path
value within the new-method/constructor, without the values lifetime beeing ended. - I changed the value of the field to
PathBuf
. My innor monk told me, thatPath
is more suitable for static configuration than thePathBuf
, which is meant to be passed around - and less efficient on the heap.
By struggling around solving my initial use case, I wondered what would be the best design, to create and organize some initial configuration for my program, which I than can use all over my program?
Do you have the Rust idiomatic answer for me?
Thanks in advance for suggestions.