Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of a C preprocessor-like #define for an array length? [duplicate]

Tags:

rust

I am writing a test to see the time difference on different buffer sizes when reading from a stream. Instead of changing the buffer size everywhere in the code, it would be nice to have some preprocessor doing it for me so that I will only need to change the value in one place.

An example of what I'm thinking of is writing a C macro define BUFFER 1024, and when creating a array using it to define the size.

like image 738
Olof Avatar asked Jul 18 '17 09:07

Olof


1 Answers

Use const to fulfill your need:

const BUFFER: usize = 512;

However, this is not preprocessor: as underscore_d's comment says, the usage of preprocessor is a pretty archaic mechanism. It has been replaced in Rust with:

  • const in case of literal value;
  • macros, to generate code.

You can understand the Rust's const keyword as "evaluated at compile-time". The (maybe) incoming functions evaluated at compile-time will be marked as const also.

Furthermore, even in C, using the preprocessor to create a compile-time constant is not the best practice.

like image 91
Boiethios Avatar answered Oct 11 '22 15:10

Boiethios