Export unwrapped value

Hello world. I'm new to rust. A certain function returns a Result. From one of my modules, I want to unwrap it, store its result in a variable or constant, and make this var public, so that I can use it from a my entire program without repeating the long process that gave me the value.

Please how can I do that ?

You certainly can't store it in a constant, unless the function itself is const. A constant in Rust must be computed at compile time and be equivalent to inlining the computing expression.

You can't store it in a static, for similar reasons. While a static variable is a specific place in memory and isn't inlined at use sites, it must still get its value at compile time.

The proper way is to just pass the inner value down the call stack as function parameters. It requires manually threading the value through code, but it has the benefit of explicitness and safety (unlike something like a mutable static, which is way too hard to use correctly).

1 Like

Thank you for the reply. I haven't yet a sufficient level to do all that. I will simplify my code by exporting a function that returns the value instead of exporting the value itself. How do you see that idea ?

Is it possible to force a unwrap on a const, even though it will make the compilation last longer ?

Yeah, making a separate function is likely the best approach, if you need to access that value only occasionally and are ok with recomputing it (which also means that calling the function has no side effects, e.g. it's not some file system operation).

I can't parse that question. If the function isn't marked as const, you can't use it to compute a value of a const.

1 Like

Thank you :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.