I am trying to create nested structs with multiple strings which will only be set once. For this I have decided to use &str
. How can I write this code correctly and cleanly?
#[derive(Debug)]
struct Database<'a, 'b, 'c, 'd> {
host: &'a str,
port: u32,
name: &'b str,
user: &'c str,
pass: &'d str, // Could be leave blank / unset
}
#[derive(Debug)]
pub struct Config<'a, 'b, 'c, 'd, 'e> {
file: &'a str,
database: Database<'b, 'c, 'd, 'e>,
}
impl Config<'_, '_, '_, '_, '_> {
pub fn new(f: &str) -> Self {
return Config {
file: f,
database: Database {
host: "", // Value passed by a variable subsequently read from a configuration file
port: 0, // Same
name: "", // Same
user: "", // Same
pass: "", // Same
},
};
}
}
fn main() {
let conf = Config::new("Ciao");
println!("{:?}", conf);
}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:18:16
|
18 | return Config {
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 17:5...
--> src/main.rs:17:5
|
17 | pub fn new(f: &str) -> Self {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:19:19
|
19 | file: f,
| ^
note: but, the lifetime must be valid for the lifetime `'_` as defined on the impl at 16:13...
--> src/main.rs:16:13
|
16 | impl Config<'_, '_, '_, '_, '_> {
| ^^
note: ...so that the expression is assignable
--> src/main.rs:18:16
|
18 | return Config {
| ________________^
19 | | file: f,
20 | | database: Database {
21 | | host: "", // Value passed by a variable subsequently read from a configuration file
... |
26 | | },
27 | | };
| |_________^
= note: expected `Config<'_, '_, '_, '_, '_>`
found `Config<'_, '_, '_, '_, '_>`