Idiomatically using optional features in an app

Hi all,

I'm not sure the best way to describe what I'm trying to figure out, as the words that come to mind have specific meanings in Rust. If there is a term for this, please do let me know! :slight_smile:

So, I have an app that can send metrics to a backend which is super useful. However, I only want to do that if it is defined in the config file. I'm using config to handle that side of things and it works really well. The metrics part of the config is held in an Option. I've tried a few ways of using the config, but something like is where I've ended up:

if let Some(metrics_config) = get_metrics_config() {
  ..
}

I create a number of things inside the if block that I need back at the top level in the main function (such as the Tokio async handle). I've tried a few things, such as making a tuple with the values I care about and using that as the last expression but that seems a bit awkward:

let result = if let Some(metrics_config) = get_metrics_config() {
  ..
  ..
  (thing_a, thing_b, thing_c)
}

What would be a more idiomatic way to do this? Or should I be taking a totally different approach?

Thanks so much!

I'm not sure about your overall use of the configuration variables, but you may take a look at this Playground for some examples of what you can do. (Note that the tuple in the Playground just serves as any data structure that would be returned by get_metrics_config, it doesn't need to be a tuple, of course.)

@jbe thank you so much for taking the time to write out such a full example! I'm going to go play with it now :slightly_smiling_face:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.