error[E0597]: `config` does not live long enough
--> src\main.rs:33:30
|
32 | let config = Config {foo: String::from("foo")};
| ------ binding `config` declared here
33 | let client = Client::new(&config);
| ------------^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `config` is borrowed for `'static`
...
40 | }
| - `config` dropped here while still borrowed
I tried to eliminate rouille from this minimal example but then the issue doesn't happen, so I'm guessing it has to do with the threaded nature of rouille.
Sure, I could clone the Config here, it's just a couple of strings, but I was wondering if there is a way to not duplicate the Config.
Make the client own Config, and don't use temporary scope-bound references in structs.
If the Config is large and you want to store it "by reference", then use Box<Config>. If one config instance must be reused many times and is too expensive to copy, then use Arc<Config>.
A temporary view & is just not flexible enough and there are plenty of cases where it's impossible to use it, at least not without causing memory leaks. In your case it won't be possible to send Client to another thread (I guess that's where 'static requirement comes from), because that would create a self-referential type.
You should avoid putting temporary references in structs.
I think @kornel means that you could solve the problem by removing the lifetime from ConfigClient and cloning your Config where needed. The Box would just keep the Client smaller in size (it's not solving your lifetime problem). This is how it could work with Box: Playground. Or without Box: Playground.
The Arc, in contrast, allows you avoiding cloning the Config.