I'm quite new to Rust (with a background in some JVM languages) and I'm stuck with the following thing:
It is kind of hard for me to describe what I exactly want to achieve without some context, so I try to provide as much as possible:
Given is a CLI application that uses Clap for argument handling. Based on the fact that a value-taking argument is present (matching the value of the argument against Some/None), I want to create an instance of a struct that holds a value of a rocksdb using the path from the argument. When the argument is not passed, the instance must not be created and therefore no handle to the rocksdb is created.
let opt_log_compact_tracking = match matches.value_of("count-alive-keys") {
Some(path) => Some(LogCompactionKeyMetrics::new(path)),
None => None
};
The resulting Some is later to be used by another function to discover, if the feature has been enabled or not in order to call a function on the struct or not.
The function on the struct needs &mut self, therefore I somehow need to pass a mutable ref, wrapped in Some(), to my function (as far as I understood).
I came up with prepending &mut in above's code Some(&mut LogCompactionKeyMetrics::new(path)),, but this makes the created struct not survive long enough.
You have a Option<LogCompactionKeyMetrics> value, by the looks of it. This Option owns the inner value, and you can take it out of there (if you need) or can borrow it mutably to call a &mut self method. So the code in your snippet looks fine, you don't need to change anything. How are you trying to call this method in question?
Thanks for all the hints so far. As far as I understood, the Option<&T> needs the referenced type to outlive the inner block of the creation, is that correct?
This is splitting hairs a bit, but it'd be more idiomatic to pass it as opt_log_compact_tracking.as_mut() rather than as &mut opt_log_compact_tracking (and hence the function takes a Option<&mut LogCompactionKeyMetrics> parameter). The use site would then just be log_compaction_metrics.map(...).