How do I do certain stuff during compile time rather than run time?

So lets say I wanted to have a tuple.

fn main()
    let tuple = ("Hello", "world");

Now lets say I am not too sure if I am going to add more values so during compile time, how would I get the tuple to add or remove certain values?

Don’t treat a tuple like a list. It’s more like an ad-hoc struct / record where the fields don’t have names. If you want a list of strings that you can add or remove values from/to at run-time you could try to use a Vec<String>.

Edit: Wait, you say you don’t want to do things at run-time … I’m not really sure what exactly you’re asking for.


Macros are the main do-general-stuff-at-compile-time mechanism in Rust, but I don’t think it’s entirely clear what you’re asking. Do you mean:

let tuple = ("Hello", "world");
//           ^^^^^^^^^^^^^^^^-----Generate this bit at compile time

Or to do something like tuple.append(2.5) /* Does not work as written! */?

Either way, you’d need to use macros, and beware that the type of the generated tuple is dependent on the types and number of elements, so code that uses the tuple will be limited to generic operations.

1 Like

Macros do seem the most likely candidate here. Depending on the exact need, however, there are a few additional options:

  • const functions
  • Type-system programming.
1 Like

I was asking like during compile time, I want the tuple to construct itself with its own list based on certain conditions.

I believe perhaps a cfg! might be helpful for this but I am not too sure?

There's not enough information here to give a recommendation. We need to know things like:

  • What sort of conditions does the code need to consider?
  • Will the number and/or type of tuple elements change based on these conditions, or just the values?
  • How will the tuple be used after it's constructed?

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.